Hiya,
I have a small problem I need to solve and I haven't found an elegant solution which leads me to believe I am missing something.
I have created a generic class, lets call it "MyClass<T>" I want it to store different Enums that I've defined as type T. I want to be able to cast the type T to a UInt16 (ushort) and also take a UInt16 and cast it back to type T.
Example:
public enum MyEnum { This, Is, A, Test } public class MyClass<T> { private T m_EnumValue; public MyClass(T enumValue) { m_EnumValue = enumValue; } public void Start() { UInt16 temp = (UInt16)m_EnumValue; T value = (T)temp; } } static void Main(string[] args) { MyClass<MyEnum> temp = new MyClass<MyEnum>(MyEnum.This); a.Start(); } |
I know I can use the cosntraint "where T: IConvertable" to allow conversion to UInt16 but I don't need it to be convertable to all the other value types that IConvertable supports and it doesn't solve the converting back to type T from UInt16. Is there not a way to specify that a generic type is of type Enum or can be converted to/from a specific value type
I understand that I can perform the cast by boxing the UInt16 into an object first and then explicitly casting to type T, but this gives no indication to user programming against my class that it requires only Enums for type T.
Thanks,
Chris

Explicit Conversion to UInt16 on Generic Type using Enums
Paully_l
Perhaps you are right, I've wanted to something similar to this before, it would be immensley helpful if generics supported static constraints such as operators and casting. Oh well, I'll go with my hacked method which using object boxing and assume *shudder* that T can be cast to UInt16 (I'll sprinkle comments all over the place
).
Chris
Dominik Ras
where
T: struct, IConvertible, IComparable<UInt16>but you don't end up with terribly pretty or efficient code. (To code your round-tripping methods, you have to resort to reflection and/or conversion to/from System.String.) You also cannot assert that the enum must be based on an UInt16 using a generic type constraint.
You may want to consider a code generation technique such as CodeSmith to solve this type of problem as Generics really don't seem to fit well.