1

I have a few questions about generic classes with Enums.

First of all, I declared my class like this:

public class MyClass<TEnum> where TEnum : struct, IConvertible

But, I'm getting an error that states that my class cannot be used with type arguments.

Moreover, I need to convert the Enum's value to an Integer. How can I do that?

public void SomeMethod(TEnum value)
{
    int a = (int)value; // Doesn't work, need to cast to Enum first (?).
}

Thanks.

user3865229
  • 125
  • 2
  • 9

2 Answers2

1

You already have what you need since you declared requirement IConvertible. Just use ToInt32 etc methods:

public class MyClass<TEnum> where TEnum: struct, IConvertible
{        
    public int SomeMethod(TEnum value)
    {
        return value.ToInt32(null);
    }
}

For example .NET type decimal is a struct and an IConvertble:

MyClass<decimal> test = new MyClass<decimal>();
Console.WriteLine(test.SomeMethod(150m));

For other classes be sure that you implement IConvertible.

ApceH Hypocrite
  • 1,093
  • 11
  • 28
0

You have declared your generic type parameter to implement IConvertible and that interface has a ToInt32 method.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
  • Hey, I know you from VBForums, hehe. I remember your dog avatar! Anyways, ToInt32 requires some FormatProvider...? Also, ToInt32 uses Convert. Isn't it easier to use Convert.ToInt32(value)? – user3865229 Aug 05 '14 at 05:50
  • You should be able to simply use `null` for the parameter value. You probably can just as easily use `Convert.ToInt32`. – jmcilhinney Aug 05 '14 at 06:03