I’m working with the new Task Parallel Library and today went to this case:
This code doesn’t compile:
internal Task<Guid?> SavePages(string[] pages)
{
return Task.Run(() =>
{
if (pages == null || pages.Length == 0)
return null;
....
Unless I explicitly returns 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 this behavior, I’m I doing something wrong? I mean, I get the code to work with the second option but don’t know If I’m misusing the library, I mean, null is always null, isn’t it?
Compile error:
Cannot convert lambda expression to delegate type
‘System.Func’ because some of the return
types in the block are not implicitly convertible to the delegate
return type
This has to do with the way the compiler determines the type of your lambda. When you return a plain
null, the only thing the compiler can imply is that you are returning an object. Hence, your parameterless lambda is compatible withTask<object>. However, the signature of your function says that you are returningTask<Guid?>, so the return type the compiler implied from your code is not compatible. When you cast thatnulltoGuid?, you provide the compiler a the clue it is missing to make the lambda aTask<Guid?>.