Expression bodied Function Weird Behavior

80 views Asked by At

When I am using

    var frontPage = await GetFrontPage();

    protected override async Task<WordDocument> GetFrontPage()
    {
        return null;
    }

This code works fine and I am getting null value in frontpage variable. but when I am rewriting the function as

protected override Task<WordDocument> GetFrontPage() => null;

I am getting an NullReferenceException.

Could anyone help me to understand the difference between the two statements.?

3

There are 3 answers

0
Jon Skeet On BEST ANSWER

Could anyone help me to understand the difference between the two statements.?

Your first declaration is async, so the compiler generates appropriate code to make it return a Task<WordDocument> which has a result with the result of the method. The task itself is not null - its result is null.

Your second declaration is not async, therefore it just returns a null reference. Any code awaiting or otherwise-dereferencing that null reference will indeed cause a NullReferenceException to be thrown.

Just add the async modifier to the second declaration and it'll work the same as the first.

Note that there are no lambda expressions here - your second declaration is an expression-bodied method. It just uses the same syntax (=>) as lambda expressions.

1
Oleksandr Veretennykov On

try with:

Func<Task<WordDocument>> frontPage = async () => await GetFrontPage();

protected override async Task<WordDocument> GetFrontPage() => await Task.FromResult<WordDocument>(null);
1
Srikrishna Sharma On

This works for me:

    protected override async Task<WordDocument> GetFrontPage() => await Task.FromResult<WordDocument>(null);