Generic: how to cast to the type specified by a type parameter?

Hi,

If I have a generic class like this:

public ClassA<T>

{

private T val;

...

}

The T can be some numeric types. Now, if I want to add a constructor, which contains:

val = Math.Pow(2.0);

The compiler will complain "can't implicitly convert 'double' to 'T'". So how to do it correctly here

Thanks in advance,

Shu



Answer this question

Generic: how to cast to the type specified by a type parameter?

  • Clintonf

    Thanks a lot, Mattias!
  • cshood

    Try it like this

    val = (T)Convert.ChangeType(Math.Pow(2.0), typeof(T));

    Also, Math.Pow takes two arguments, but that's another issue.



  • Generic: how to cast to the type specified by a type parameter?