In C# can I cast a variable of type object
to a variable of type T
where T
is defined in a Type
variable?
Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char.
Variables are containers for storing data values. In C#, there are different types of variables (defined with different keywords), for example: int - stores integers (whole numbers), without decimals, such as 123 or -123. double - stores floating point numbers, with decimals, such as 19.99 or -19.99.
You convert an Object variable to another data type by using a conversion keyword such as CType Function.
Here is an example of a cast and a convert:
using System; public T CastObject<T>(object input) { return (T) input; } public T ConvertObject<T>(object input) { return (T) Convert.ChangeType(input, typeof(T)); }
Edit:
Some people in the comments say that this answer doesn't answer the question. But the line (T) Convert.ChangeType(input, typeof(T))
provides the solution. The Convert.ChangeType
method tries to convert any Object to the Type provided as the second argument.
For example:
Type intType = typeof(Int32); object value1 = 1000.1; // Variable value2 is now an int with a value of 1000, the compiler // knows the exact type, it is safe to use and you will have autocomplete int value2 = Convert.ChangeType(value1, intType); // Variable value3 is now an int with a value of 1000, the compiler // doesn't know the exact type so it will allow you to call any // property or method on it, but will crash if it doesn't exist dynamic value3 = Convert.ChangeType(value1, intType);
I've written the answer with generics, because I think it is a very likely sign of code smell when you want to cast a something
to a something else
without handling an actual type. With proper interfaces that shouldn't be necessary 99.9% of the times. There are perhaps a few edge cases when it comes to reflection that it might make sense, but I would recommend to avoid those cases.
Edit 2:
Few extra tips:
object
or dynamic
variable.Other answers do not mention "dynamic" type. So to add one more answer, you can use "dynamic" type to store your resulting object without having to cast converted object with a static type.
dynamic changedObj = Convert.ChangeType(obj, typeVar); changedObj.Method();
Keep in mind that with the use of "dynamic" the compiler is bypassing static type checking which could introduce possible runtime errors if you are not careful.
Also, it is assumed that the obj is an instance of Type typeVar or is convertible to that type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With