Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a variable using a Type variable

In C# can I cast a variable of type object to a variable of type T where T is defined in a Type variable?

like image 340
theringostarrs Avatar asked Jun 09 '09 21:06

theringostarrs


People also ask

How do you cast a type?

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.

What is type variable in C#?

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.

Is used to convert an object or variable of one type into another?

You convert an Object variable to another data type by using a conversion keyword such as CType Function.


2 Answers

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:

  • Try to keep your code as type-safe as possible. If the compiler doesn't know the type, then it can't check if your code is correct and things like autocomplete won't work. Simply said: if you can't predict the type(s) at compile time, then how would the compiler be able to?
  • If the classes that you are working with implement a common interface, you can cast the value to that interface. Otherwise consider creating your own interface and have the classes implement that interface.
  • If you are working with external libraries that you are dynamically importing, then also check for a common interface. Otherwise consider creating small wrapper classes that implement the interface.
  • If you want to make calls on the object, but don't care about the type, then store the value in an object or dynamic variable.
  • Generics can be a great way to create reusable code that applies to a lot of different types, without having to know the exact types involved.
  • If you are stuck then consider a different approach or code refactor. Does your code really have to be that dynamic? Does it have to account for any type there is?
like image 111
Zyphrax Avatar answered Oct 14 '22 02:10

Zyphrax


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.

like image 32
maulik13 Avatar answered Oct 14 '22 01:10

maulik13