Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the new 'dynamic' C# 4.0 keyword deprecate the 'var' keyword?

When C# 4.0 comes out and we have the dynamic keyword as described in this excellent presentation by Anders Hejlsberg, (C# is evolving faster than I can keep up.. I didn't have much time to acquaint myself with the var keyword)

Would I still need the var keyword ? Is there anything that var can do.. that dynamic can't?

var x = SomeFunctionThatIKnowReturnsSomeKindOfList(); // do something with x  dynamic x = SomeFunctionThatIKnowReturnsSomeKindOfList(); // do something with x 
like image 234
Gishu Avatar asked Nov 18 '08 09:11

Gishu


People also ask

Should I use Dynamic C#?

Dynamic should be used only when not using it is painful. Like in MS Office libraries. In all other cases it should be avoided as compile type checking is beneficial.

What is the dynamic type in C#?

In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.

Is C sharp dynamic or static?

C# and Java are often considered examples of statically typed languages, while Python, Ruby and JavaScript are examples of dynamically typed languages.

Which of the following is true for dynamic type in C sharp?

When an object type is converted to a value type, it is called unboxing. Q 17 - Which of the following is correct about dynamic Type in C#? A - You can store any type of value in the dynamic data type variable. B - Type checking for these types of variables takes place at run-time.


1 Answers

No, they're very different.

var means "infer the type of the variable at compile-time" - but it's still entirely statically bound.

dynamic means "assume I can do anything I want with this variable" - i.e. the compiler doesn't know what operations are available, and the DLR will work out what the calls really mean at execution time.

I expect to use dynamic very rarely - only when I truly want dynamic behaviour:

  • var lets you catch typos etc at compile-time
  • statically bound code is always going to run faster than dynamically bound code (even if the difference becomes reasonably small)
  • statically bound code gives more compile-time support beyond just errors: you can find call hierarchies, refactoring will work better, Intellisense is available etc
like image 129
Jon Skeet Avatar answered Sep 23 '22 18:09

Jon Skeet