Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I dont want to use ! everywhere, preferably never

>Solution :

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.

Unfortunately, pre-C#9, there doesn’t appear to be a way of annotating this. You can use [AllowNull] TSource source, but that doesn’t stop TSource from being inferred as nullable. Defining your own delegate doesn’t seem to help either.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading