0

I need to have information about maximum value of enum i method with generics..

public static T DoSomething<T>() where T : struct, IConvertible, IComparable, IFormattable
{
    T pom1 = Enum.GetValues(typeof(T)).Cast<T>().Max();
...

In pom1 is value of maximum possible value of T (enum) - it works. But when I want to get int from pom1, its problem.

int pom4 = (int)pom1;

I tryied something like this:

int pom4 = (int)(ValueType)pom1;

Still error like "Specific cast is not valid"

Thanks of any help.

  • 2
    Possible duplicate of http://stackoverflow.com/q/16960555/613130 – xanatos Apr 10 '15 at 14:00
  • Possible duplicate of [How do I cast generic enum to int?](https://stackoverflow.com/questions/16960555/how-do-i-cast-generic-enum-to-int) – NtFreX Jun 25 '18 at 13:50

1 Answers1

2

using VS2008 .Net 3.5

    static void Main(string[] args)
    {
        DoSomething<ConsoleKey>();
        Console.ReadKey(true);
    }

    public static T DoSomething<T>() where T : struct, IConvertible, IComparable, IFormattable
    {
        T pom1 = Enum.GetValues(typeof(T)).Cast<T>().Max();
        Console.WriteLine(pom1);
        //Cast to object to bypass bits of the type system...Nasty!!
        int pom4 = (int)(object)pom1;
        Console.WriteLine(pom4);
        //Use Convert
        int pom5 = Convert.ToInt32(pom1);
        Console.WriteLine(pom5);
        //Take advantage of passing a IConvertible
        int pom6 = pom1.ToInt32(System.Globalization.CultureInfo.CurrentCulture);
        Console.WriteLine(pom6);
        return pom1;
    }

And the Output...

OemClear
254
254
254

James
  • 9,774
  • 5
  • 34
  • 58