'How to resolve "possible System.NullReferenceException" while acquiring token

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stefan