Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a dynamic variable to a given Type

Tags:

c#

dynamic

c#-4.0

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.

like image 477
eka808 Avatar asked Feb 17 '26 18:02

eka808


2 Answers

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();
like image 133
SLaks Avatar answered Feb 19 '26 07:02

SLaks


((Foo)myvar).mymethodoffoo();
((Bar)myvar).mymethodofbar();
like image 36
tzup Avatar answered Feb 19 '26 08:02

tzup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!