C# Convert Generic Type

April 3, 2011

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 use 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. (for search engines:...
tags: ,
no comments