-1

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

Charlieface
  • 52,284
  • 6
  • 19
  • 43

3 Answers3

5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

try with:

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

protected override async Task<WordDocument> GetFrontPage() => await Task.FromResult<WordDocument>(null);
  • `protected override Task GetFrontPage() => Task.FromResult(null);` shorter and less overhead – Firo Mar 01 '23 at 08:34
-1

This works for me:

    protected override async Task<WordDocument> GetFrontPage() => await Task.FromResult<WordDocument>(null);
  • 1
    `protected override Task GetFrontPage() => Task.FromResult(null);` shorter and less overhead – Firo Mar 01 '23 at 08:34