Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using get type and then casting to that type in C#

I have code like:

var t = SomeInstanceOfSomeClass.GetType();
((t)SomeOtherObjectIWantToCast).someMethodInSomeClass(...);

That won't do, the compiler returns an error about the (t) saying Type or namespace expected. How can you do this?

I'm sure it's actually really obvious....

like image 252
Matt Avatar asked Oct 18 '25 13:10

Matt


2 Answers

C# 4.0 allows this with the dynamic type.

That said, you almost surely don't want to do that unless you're doing COM interop or writing a runtime for a dynamic language. (Jon do you have further use cases?)

like image 178
Sam Harwell Avatar answered Oct 21 '25 02:10

Sam Harwell


I've answered a duplicate question here. However, if you just need to call a method on an instance of an arbitrary object in C# 3.0 and below, you can use reflection:

obj.GetType().GetMethod("someMethodInSomeClass").Invoke(obj);
like image 42
mmx Avatar answered Oct 21 '25 04:10

mmx