This is what I need to do:
object foo = GetFoo();
Type t = typeof(BarType);
(foo as t).FunctionThatExistsInBarType();
Can something like this be done?
cast() method casts an object to the class or interface represented by this Class object.
You convert an Object variable to another data type by using a conversion keyword such as CType Function.
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.
You can use the Convert.ChangeType method.
object foo = GetFoo();
Type t = typeof(string);
string bar = (string)Convert.ChangeType(foo, t);
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.)
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