Passing a generic parameter to a non-generic method

I am trying to create a method that will round nullables to the given decimal place. Ideally, I would like this to be common, so that I can use it with both two and decimal words, as it allows Math.Round().

The code that I wrote below will not compile, because the method cannot be (understandably) allowed, since it is impossible to know which overload to call. How will 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)'
 }
+3
source share
2 answers

How will this be achieved?

Personally, I would just get rid of your general method. It is valid for only two type arguments - break 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;
}

, , , dynamic, # 4 .NET 4.

+7

, , :

if (paramType == typeof(decimal?))
...
    Math.Round((decimal)nullable.Value, decimals)
else if(paramType == typeof(double?))
    Math.Round((double)nullable.Value, decimals)
+2

All Articles