2
votes

I am following the sample code provided in "Azure-Sample" to acquire token to call Microsoft Graph Api. But Resharper suggesting "Possible System.NullReferenceException" in await app.AcquireTokenForClient(scopes) .ExecuteAsync(); How to resolve NullReference exception?

Clone the code and seeing "Possible System.NullReferenceException"

AuthenticationResult result = null;
            try
            {
                result = await app.AcquireTokenForClient(scopes)
                    .ExecuteAsync();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Token acquired");
                Console.ResetColor();
            }
            catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
            {
                // Invalid scope. The scope has to be of the form "https://resourceurl/.default"
                // Mitigation: change the scope to be as expected
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Scope provided is not supported");
                Console.ResetColor();
            }

enter image description here

Resharper is suggesting "Possible System.NullReferenceException", any idea how to resolve?

2

2 Answers

2
votes

"Pessimistic" value analysis mode is enable in ReSharper and it thinks everything can be "null" unless it is explicitly checked for null or annotated with "NotNull" or "ContractAnnotation" attribute. Some options to handle this case:

  1. Provide external annotations for "AcquireTokenForClient"
  2. extract "app.AcquireTokenForClientAsync(scopes)" to a local variable and check it for null:

    var task = app.AcquireTokenForClientAsync(scopes); if (task == null) throw new Exception(); result = await task;

  3. Enable "Optimistic" value analysis mode

1
votes

The way to handle such case is to check for null and raise an exception if it is.

Assuming app is an input variable of your method:

void Foo(IApp app) //just using IApp as an example.
{
    if (app == null)
        throw new ArgumentNullException(nameof(app));

    var result = app.Bar(); //no possible null ref here.
}