Reputation: 2317
I have a dynamic variable where i store, depending of the context, an object who can be of several types (here Foo and Bar)
dynamic myvar;
myvar = new Foo();
//or
myvar = new Bar();
Foo and Bar contains differents methods. To get access to methods of myvar, i thought it was possible to use casts like
(Foo)myvar.mymethodoffoo();
(Bar)myvar.mymethodofbar();
But it's not working, i get (dynamic expression) this operation will be resolved at runtime in the code editor.
So, How can i cast a dynamic object to get the available methods and properties from the editor ?
Thank's by advance.
Upvotes: 3
Views: 3719
Reputation: 887195
The cast operation ((SomeType)x
) has a lower precedence than the .
.
Therefore, your code is parsed as (Bar)(myvar.mymethodofbar())
— the cast happens after the method call.
You need to add parentheses:
((Bar)myvar).mymethodofbar();
Upvotes: 10