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....
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?)
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);
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