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:
Map
can be called onnull
.- Even if
Map
is called onnull
, theFunc
parameter will not be called with anull
input Map
can returnnull
, even in cases where theFunc
does 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
).
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.