Search code examples
c#.netasync-awaitnullreferenceexceptionexpression-body

Expression bodied Function Weird Behavior


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.?


Solution

  • 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.