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.
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();
((Foo)myvar).mymethodoffoo();
((Bar)myvar).mymethodofbar();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With