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
>Solution :
So:
Mapcan be called onnull.- Even if
Mapis called onnull, theFuncparameter will not be called with anullinput Mapcan returnnull, even in cases where theFuncdoes not returnnull
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).
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.