Matt
Matt

Reputation: 27001

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

Upvotes: 4

Views: 15361

Answers (4)

Ben Lesh
Ben Lesh

Reputation: 108501

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.

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422182

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

Upvotes: 3

Sam Harwell
Sam Harwell

Reputation: 99989

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

Upvotes: 8

Joseph
Joseph

Reputation: 25523

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.

Upvotes: 0

Related Questions