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)'
}
How would this be achieved?
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:
internal static double? RoundNullable(double? nullable, int decimals)
{
return nullable.HasValue ? Math.Round(nullable.Value, decimals)
: (double?) null;
}
internal static decimal? RoundNullable(decimal? nullable, int decimals)
{
return nullable.HasValue ? Math.Round(nullable.Value, decimals)
: (decimal?) null;
}
If you must use the generic version, either invoke it conditionally as per Dave's answer, invoke it with reflection directly, or use dynamic if you're using C# 4 and .NET 4.
Given you're already doing a type-check, simply use that in your code flow:
if (paramType == typeof(decimal?))
...
Math.Round((decimal)nullable.Value, decimals)
else if(paramType == typeof(double?))
Math.Round((double)nullable.Value, decimals)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With