Search code examples
c#generics

How do I get the max and min value of a generic number type in c#


I have a generic type called TValue. I want to do something like this:


public TValue Number {get;set;}
public TValue GetMaxNumber()
{
   switch (Number)
   {
       case int @int:
           if (@int == default(int))
           {
               return int.MaxValue;
           }
       case long @long:
           //get max value of long
       case short @short:
           //get max value of short
       case float @float:
           //get max value of float
       case double @double:
           //get max value of double
       case decimal @decimal:
           //get max value of decimal
       default:
           throw new InvalidOperationException($"Unsupported type {Number.GetType()}");
    }
}

I want the GetMaxNumber method to return the maximum possible value for that number type. If it is not a number type then throw an exception.

The main issue I have here is that I don't understand how to convert something like an int back to the original generic type, while using int's properties, such as MaxValue.

How do I make this work?


Solution

  • You can convert it this way:

    return (TValue)(object)int.MaxValue;
    

    Boxing allows to unbox to the relevant generic type parameter.