I’m attempting to create a method which will round nullables to a given decimal place. Ideally I’d like this to be a generic so that I can use it with both Doubles and Decimals as Math.Round() permits.
The code I have written below will not compile because the method cannot be (understandably) resolved as it’s not possible to know which overload to call. How would this be achieved?
internal static T? RoundNullable<T>(T? nullable, int decimals) where T : struct
{
Type paramType = typeof (T);
if (paramType != typeof(decimal?) && paramType != typeof(double?))
throw new ArgumentException(string.Format("Type '{0}' is not valid", typeof(T)));
return nullable.HasValue ? Math.Round(nullable.Value, decimals) : (T?)null; //Cannot resolve method 'Round(T, int)'
}
Personally, I would just get rid of your generic method. It’s only valid for two type arguments anyway – split it into an overloaded method with two overloads:
If you must use the generic version, either invoke it conditionally as per Dave’s answer, invoke it with reflection directly, or use
dynamicif you’re using C# 4 and .NET 4.