Pass generic parameter to a non-generic method

.net, c#, generics, overloading

Solution

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.

Problem

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)' } ```

Original source