Slack Groverglow
Slack Groverglow

Reputation: 856

Why does async extension method throw System.NullReferenceException

I have two extension methods, that pretty much do the same thing but one is async

public static class ProjectExtensions
{
   public static Layout GetLayout(this Project project)
   {
      ..
   }

   public static async Task<Layout> GetLayoutAsync(this Project project)
   {
      ...
   }
}

And I'm using the .? operator because I don't want to call these methods if the project is null:

public async Task<Layout> GetMapFrameLocator()
{    
   Project currentProject = Project.Current;             // this can be null
   var layout1 = await currentProject?.GetLayoutAsync(); // throws!
   var layout2 = currentProject?.GetLayout();            // works fine
}

Neither methods actually get called, which I expected, but the async one throws a null reference exception which doesnt make sense to me because nothing gets called with the null Project. I know this issue will go away if I use . instead of .? and handle the null parameter in the static extension method, but whats the reason this for this exception and why is the async method different?

Upvotes: 1

Views: 118

Answers (1)

GazTheDestroyer
GazTheDestroyer

Reputation: 21261

await requires a Task to await.

If your currentProject is null then the expression currentProject?.GetLayoutAsync() will resolve to null. await cannot await null

Upvotes: 8

Related Questions