dealing with "possible null reference return" when implementing external interfaces on projects that enable nullable

Viewed 630

I have the following interface that needs to get implemented, returning default if not finding the role generates warning CS8603 Possible null reference return.

    public async Task<ApplicationRole> FindRoleByIdAsync(string roleId, CancellationToken cancellationToken = default)
    {
       //find the role based on ID return it if found else
       return default;
    }

I can't change the interface and make it nullable as my influence over Microsoft are not at that level... so I guess update it with an annotation (does not make the warning go away)

    [return: MaybeNull]
    public async Task<ApplicationRole> FindRoleByIdAsync(string roleId, CancellationToken cancellationToken = default)
    {
       //find the role based on ID return it if found.. else 
       return default;
    }

what is the correct way to implement this, any suggestions?

2 Answers

Just try to not return a Null value

public async Task<ApplicationRole> FindRoleByIdAsync(string roleId, CancellationToken cancellationToken = default)
    {
       //find the role based on ID return it if found.. else 
       return default ?? new ApplicationRole();
    }

For deep-dive visit MSDN documentation. As per MSDN:

Apply the null forgiving operator ! to the expression to force the state to not-null.

public async Task<ApplicationRole> FindRoleByIdAsync(String roleId, CancellationToke cancellationToken = default)
{
    //Your code
    return default!;
}

or

public async Task<ApplicationRole> FindRoleByIdAsync(String roleId, CancellationToke cancellationToken = default)
{
    //Your code
    return null!;
}
Related