Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is possible to cast a variable to a type stored in another variable?

Tags:

c#

casting

This is what I need to do:

object foo = GetFoo();
Type t = typeof(BarType);
(foo as t).FunctionThatExistsInBarType();

Can something like this be done?

like image 684
Marek Grzenkowicz Avatar asked Jan 21 '09 10:01

Marek Grzenkowicz


People also ask

Which is used for casting of object to a type or a class?

cast() method casts an object to the class or interface represented by this Class object.

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.

How do you type a cast?

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.


2 Answers

You can use the Convert.ChangeType method.

object foo = GetFoo(); 
Type t = typeof(string);
string bar = (string)Convert.ChangeType(foo, t);
like image 148
GvS Avatar answered Oct 10 '22 08:10

GvS


No, you cannot. C# does not implement duck typing.

You must implement an interface and cast to it.

(However there are attempts to do it. Look at Duck Typing Project for an example.)

like image 32
Quassnoi Avatar answered Oct 10 '22 07:10

Quassnoi