C# Dynamic Keyword

dynamic is a new static type that acts like a placeholder for a type not known until runtime. Once the dynamic object is declared, it is possible to call operations, get and set properties on it, even pass the dynamic instance pretty much as if it were any normal type.

The dynamic keyword influences compilation. A dynamic variable, parameter or field can have any type. Its type can change during runtime. The downside is that performance suffers and you lose compile-time checking.

Dynamic is advanced functionality. It can be useful. But usually it should be avoided. It erases many benefits of the C# language.

Comparison with var
dynamic variable and var variable both can store any type of value but its required to initialize ‘var’ at the time of declaration.

Compiler doesn’t have any information about the ‘dynamic’ type of variable. var is compiler safe i.e compiler has all information about the stored value, so that it doesn’t cause any issue at run-time.

Dynamic type can be passed as function argument and function also can return it. Var type can not be passed as function argument and function can not return object type. This type of variable can work in the scope where it defined.

dynamic: Useful when coding using reflection or dynamic language support or with the COM objects, because we require to write less amount of code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s