C#4.0 Dynamic Vs Var keyword

In C# 4.0 we have a new keyword called dynamic, I can use it as with any types like int, float,double, string

after reading above line, we all have question “What’s new in that?, I can also do this with Var keyword.” the answer is “Yes”, We can still do the same thing with Var keyword,but it has a different behavior, Let me explain you with the example

when you declare a variable with Var keyword, var are  implicitly but statically typed, let me explain the meaning of that.

when you write like below compiler figured out that someString must be of type string (i.e. from initialize) and then it will use reflection to get all information about the type at the compile time.(See below pic)

Var someString = "Some String Example";

Similarly when you use dynamic keyword instead of var, it will behave differently, it will behave most similar to object.

With dynamic, properties / methods / operators / etc are resolved at runtime, based on the actual object

According to the MSDN blog “Variables declared with var are implicitly but statically typed. Variables declared with dynamic are dynamically typed. This capability was added to the CLR in order to support dynamiclanguages like Ruby and Python.”


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s