Home > Enterprise >  Nullable reference types, Hint static analysis that parameter is never null
Nullable reference types, Hint static analysis that parameter is never null

Time:03-09

Lets say I have this extension method

 public static TRes Map<TSource, TRes>(this TSource source, Func<TSource, TRes> mapper) 
        {
            return source is null ? default : mapper(source);
        }

usage:

myobject.Map(obj=> new OtherType(obj,1,2,3));

I get a warning that obj can be null. Is there any way, in the declaration of my extension method, that I can hint static analysis that obj cant be null, since mapper will not be called if obj is null.

I dont want to use ! everywhere, preferably never

CodePudding user response:

So:

  1. Map can be called on null.
  2. Even if Map is called on null, the Func parameter will not be called with a null input
  3. Map can return null, even in cases where the Func does not return null

Put this together, and:

public static TRes? Map<TSource, TRes>(this TSource? source, Func<TSource, TRes> mapper)
{
    return source is null ? default : mapper(source);
}  

The TSource? source means that even if we call Map on a variable which may be null, TSource is still inferred as non-nullable. This means that the Func<TSource, TRes> will not receive null as its input.

The TRes? means that we're allowed to return null, even if TRes is inferred as nullable (from the signature of mapper).

See it on SharpLab.

Pre-C#9, you are only able to use ? on generic type parameters if you constrain them to be a reference or a value type: unconstrained ? was only added in C# 9. You will need to add where TSource : class where TRes : class if you are using C# 8.

  • Related