Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lambda 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 nullpointer exception

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Upvote if you find the question a valid one.
Thanks!

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading