Call function if argument not null in C#

Viewed 202

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?

1 Answers

I've got it working finally. Just created 2 overload for class and struct generic constraints:

public static TRes? CallOrNull<TArg, TRes>(this TArg? arg, Func<TArg, TRes> func)
    where TArg : struct
    => arg switch
    {
        null => default,
        { } argObj => func(argObj),
    };

public static TRes? CallOrNull<TArg, TRes>(this TArg? arg, Func<TArg, TRes> func)
    where TArg : class
    => arg switch
    {
        null => default,
        { } argObj => func(argObj),
    };

Good that it's working, still don't get why the original version did not.

Related