views:

932

answers:

4

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....

A: 

In order to cast the way you're describing in your question you have to declare the type at compile time, not run time. That is why you're running into problems.

Joseph
+2  A: 

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

280Z28
Yup, a few: Double dispatch made a lot simpler (at the loss of compile-time safety); using operators with generics; making calls to generic methods where the types are only known at execution time a lot simpler.
Jon Skeet
`dynamic` is useful in some other scenarios too, mainly, not just writing a runtime for a dynamic language but interoping with a dynamic environment (IronPython, IronRuby, Javascript, etc).
Mehrdad Afshari
@Jon - how did you know that you were being summoned?!
Russ Cam
Thanks for the input. :) I work more with implementation aspects than use cases for this type of construct.
280Z28
A: 

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);
Mehrdad Afshari
A: 
if(t is ThisType) {
    ThisType tt = (ThisType)t;
    /*do something here*/
}else if(t is ThatType) {
    ThatType tt = (ThatType)t;
    /*do something here*/
}

etc.

That's the best you can do in C# 3.5 and lower, really.

blesh