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

14,684

Solution 1

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

Solution 2

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

Solution 3

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.

Share:
14,684
Matt
Author by

Matt

Hello

Updated on June 28, 2022

Comments

  • Matt
    Matt almost 2 years

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

  • Jon Skeet
    Jon Skeet over 14 years
    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.
  • mmx
    mmx over 14 years
    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).
  • Russ Cam
    Russ Cam over 14 years
    @Jon - how did you know that you were being summoned?!
  • dalemac
    dalemac over 9 years
    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.