I have a System.Type stored in a variable. I wish to Change an object’s type to this type.
I have the following code, but cannot get the Type to change to the type.
Ideally I’d like: var intTest3 =(MyType)Convert.ChangeType(test, MyType); to return an int, when : MyType is a System.Int32
Here’s my working so far – where am I going wrong?
// object to cast to int
object test = 1;
// INT32 type
Type MyType = typeof(System.Int32);
// explicit type int WORKS
var intTest = (int)Convert.ChangeType(test, typeof(Int32));
// explicit type to int WORKS
var intTest2 = (int)Convert.ChangeType(test, MyType);
// explicit type to int WORKS - but as object
object intTest3 = Convert.ChangeType(test, MyType);
// cast to my type DOESNT WORK
var intTest3 =(MyType)Convert.ChangeType(test, MyType);
Thank you!
This isn’t really about
Convert.ChangeType– it’s about casting. The type you’re casting to has to be known at compile time, although it could be a generic type. In this case, as far as the compiler is concernedMyTypecould refer to any type. It doesn’t “know” that it will definitely have the valuetypeof(int), so it won’t just emit a cast toint.In this case, what would you expect the compile-time type of
intTest3to be?What’s the bigger picture here? What are you really trying to do? How would you want to use the value of
intTest3?