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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Matt
  • 25,943
  • 66
  • 198
  • 303

4 Answers4

8

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

Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
  • 2
    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 Aug 11 '09 at 20:04
  • `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 Aug 11 '09 at 20:09
  • @Jon - how did you know that you were being summoned?! – Russ Cam Aug 11 '09 at 20:10
  • Thanks for the input. :) I work more with implementation aspects than use cases for this type of construct. – Sam Harwell Aug 11 '09 at 20:13
  • I have used dynamic binding when working with MVC API controllers when using model binding. For example, if you are always looking to match an API token in an ActionFilter, it is much easier to dynamically bind the model and check for the necessary parameter than to test for 20 or 30 seperate object types. – dalemac Oct 13 '14 at 13:33
3

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);
Community
  • 1
  • 1
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
1
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.

Ben Lesh
  • 107,825
  • 47
  • 247
  • 232
0

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
  • 25,330
  • 8
  • 76
  • 125