var is just another C# syntactic flavor. C# compiler infers the types for us.
Lets take a look at this code snippet,
int intX = 10;
var intY = 20;
It may look different in the surface, but both are type of Int32 in IL.
var
is static typing, this means that resolutions are verified at compile time. If we try to access a method or property that doesn't exist or beyond the access level, compiler stops the compilation. No more soup for you. Its like Soup Nazi.
string testString = "Hello";
testString.toString();
In the other hand,
dynamic
uses dynamic typing. If you try to access the method or property that doesn't exist then compiler wont stop you from compiling the code. Compiler changes its role as a controller to helper. It assumes that we know what we are doing and move out of our way.
dynamic testDynamic = "Hello Dynamic";
testDynamic.toString();
Both
var
and
dynamic
have their purposes in the framework. Its all come down to using the right tool for the right job.
var
provides support for anonymous types. It provides better readability, Imagine using LINQ chaining without anonymous methods.
class Person
{ public string Name { get; private set; } public Person(string name) { Name = name; }
}
List<Person> persons = new List<Person>() { new Person("Ordinary Joe"), new Person("Regular Rick") };
var superPersons = persons.ConvertAll(p => new { Name = p.Name, SuperPower = "Fly" });
dynamic
comes with its own set of features, It also provide better readability. Having
dynamic
objects in .NET, makes programming COM easy and readable. Code that is tough to read is tough to maintain and extend.
((Excel.Range)excelApp.Cells[1, 1]).Value2 = "Name";
Excel.Range range2008 = (Excel.Range)excelApp.Cells[1, 1];
excelApp.Cells[1, 1].Value = "Name";
Excel.Range range2010 = excelApp.Cells[1, 1];
You can change
dynamic
type from one to another with out casting or boxing/unboxing.
dynamic value;
value = 10;
value = DateTime.Now;
dynamic
also adds another great feature, dynamic member. Any code that has access to a
dynamic
type can change its type or add new properties or add new method.
dynamic
enables us doing reflection like coding without paying heavy performance penalty. Take a look at these micro ORMs like dapper-dot-net and Massive. They are so tiny and super fast. its like too good to be true.
References:
-
Using Type dynamic - MSDN
-
Access Office Interop Objects – MSDN
-
Implicitly Typed Local Variables (C# Programming Guide)
-
Dynamic Language Runtime Overview
-
Massive: 400 Lines of Data Access Happiness
-
StackOverflow dynamic vs var