Why Task doesn't return null

I am working with the new Task Parallel Library and today set off in this case:

This code does not compile:

internal Task<Guid?> SavePages(string[] pages) { return Task.Run(() => { if (pages == null || pages.Length == 0) return null; .... 

Unless I explicitly return a null nullable Guid:

  internal Task<Guid?> SavePages(string[] pages) { return Task.Run(() => { if (pages == null || pages.Length == 0) return (Guid?)null; // Check documents path access 

Why is this behavior I'm doing something wrong? I mean, I get the code to work with the second option, but I don’t know. If I use the library incorrectly, I mean that null is always null, right?

Compilation Error:

It is not possible to convert a lambda expression to the delegation type "System.Func" because part of the return types in the block are implicitly converted to the delegate return type

http://msdn.microsoft.com/en-us/library/dd460717.aspx

+4
source share
2 answers

This is due to the way the compiler determines the type of your lambda. When you return a simple null , the only thing the compiler can mean is that you return an object. Therefore, your parameterless lambda is compatible with Task<object> . However, the signature of your function says that you return Task<Guid?> , So the type of return that is meant by your code is incompatible. When do you cast null in Guid? , you provide the compiler with a key that is missing to make lambda a Task<Guid?> .

+5
source

This is a restriction on the type of output in the C # compiler. This question is not related to the one associated with the ternary operator:

 int? num = a != null ? a.Value : null; // Will not compile int? num = a != null ? a.Value : (int?)null; // Compiles int? num = a != null ? (int?)a.Value : null; // Compiles 

Another workaround for a specific situation is to explicitly specify a generic type:

 return Task.Run<Guid?>(() => { if (pages == null || pages.Length == 0) return null; 
+3
source

All Articles