Monday, April 04, 2011

C# Convert Generic Type

I am posting this because I didn't see a simple solution on the first few hits when searching the net.
If you have a generic class of type T and you want to using it with basic types such as int, long, etc. You can use the following method to do the casting:

class myClass<T>
{
   private int myVal;
   public T Get()
   {
      return ((T)(Convert.ChangeType(myVal, typeof(T))));
   }
}
enum SomeEnum { One = 1, Two = 3 }
myClass<SomeEnum> X;
SomeEnum se = X.Get();
You can also use: (TYPE)(retval as IConvertible).ToType(typeof( ....
This is relevant because native types require casting and you cannot use the 'as' keyword.

Read more: Asaf Shelly