There are several problems with the code. The first one is that your types must be nullable. You can express that by specifying where T: struct
. You will also need to specify where TResult: struct
because you're using that as a nullable type too.
Once you fix up the where T: struct where TResult: struct
you also need to change the return value type (which was wrong) and a number of other things too.
After fixing all those errors and simplifying, you wind up with this:
static TResult? ApplyFunction<T, TResult>(T? nullable, Func<T, TResult> function)
where T: struct
where TResult: struct
{
if (nullable.HasValue)
return function(nullable.Value);
else
return null;
}
Note that you can rewrite Nullable<T>
as T?
which makes things more readable.
Also you could write that as one statement using ?:
but I don't think it's as readable:
return nullable.HasValue ? (TResult?) function(nullable.Value) : null;
You might want to put this into an extension method:
public static class NullableExt
{
public static TResult? ApplyFunction<T, TResult>(this T? nullable, Func<T, TResult> function)
where T: struct
where TResult: struct
{
if (nullable.HasValue)
return function(nullable.Value);
else
return null;
}
}
Then you can write code like this:
int? x = 10;
double? x1 = x.ApplyFunction(i => Math.Sqrt(i));
Console.WriteLine(x1);
int? y = null;
double? y1 = y.ApplyFunction(i => Math.Sqrt(i));
Console.WriteLine(y1);