Subscribe to our newsletter

Crammed full of useful advice and tips from the team here at Quba.

Select choices
Warning: This post is aimed at technical people.

What is the purpose of the dynamic keyword?

Some languages such as Ruby and Python are dynamically typed. This means that a variable won’t know its type until runtime. This becomes a problem when trying to use a component written in one of these languages inside of your C# application. Before the release of .NET4, this could be achieved using reflection but there are a couple of issues with this.

Firstly, the code to do reflection is a bit clunky.

[caption id="attachment_2305" align="alignnone" width="548" caption="Example of Reflection"]Example of Reflection[/caption]

The dynamic keyword is much neater and abstracts away the complexities of dealing with dynamic components.

[caption id="attachment_2308" align="alignnone" width="223" caption="Example of Dynamic keyword"]Dynamic example[/caption]

Secondly, reflection hurts performance. The reason is that dynamic components need to be analysed at runtime using reflection, each time the component is used. The analysis is an expensive process so the Dynamic Language Runtime, which is used when using the dynamic keyword, caches the analysis and improves performance.

What is the difference between var and dynamic?

The dynamic keyword is so familiar that it looks from example code to do the exact same thing as the var keyword; i.e. replace having to specify a type with something that will be worked out for you later on. The difference is that the var keyword is replaced by a specific type at compile time rather than runtime. The var keyword cannot be used for dynamic components.

How do I avoid wreaking havoc with the dynamic keyword?

Only use the dynamic keyword when working with a dynamic component. Using the dynamic keyword gives up the compile time checks and that isn’t something that you want to do unless you absolutely have to.

If you do have to use the dynamic keyword then the best way to avoid issues are unit tests.

Further reading

Scott Hanselman's summary of the dynamic keyword

MSDN Magazine article about the dynamic keyword