With enabled nullable context in C# project, I want to create some extension method that takes a value, and if it is not null, calls the function with this argument. If argument is null, the null is returned. It's almost like non-coalescing ?. operator, but called on an arbitrary function rather than a method. And I want it to be working on both val and ref types. I tried a function
public static TRes? CallOrNull<TArg, TRes>(this TArg? arg, Func<TArg, TRes> func)
where TArg : notnull
=> arg switch
{
null => default,
{ } argObj => func(argObj),
};
on the following
int Add5(int i) => i + 5;
var expectedNull = ((int?) null).CallOrNull(Add5);
var expected_10 = ((int?) 5).CallOrNull(Add5);
This does not compile, though with an error Expected a method with 'Add5(int?)' signature.
Specifying template arguments explicitly like in
_ = ((int?) null).CallOrNull<int, int>(Add5);
does not help either. The same if I comment template specification, //where TArg : notnull.
Any ideas?