Thursday, April 21, 2011

var vs dynamic in C#

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.

image

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(); //Compile time error

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(); //Run time error.  

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;     }
    }  
    //Convert Person to SuperPerson without creating yet another class
    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.

    // Before the introduction of dynamic.
    ((Excel.Range)excelApp.Cells[1, 1]).Value2 = "Name";
    Excel.Range range2008 = (Excel.Range)excelApp.Cells[1, 1];

    // After the introduction of dynamic, the access to the Value property and
    // the conversion to Excel.Range are handled by the run-time COM binder.
    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; //Now it is Int32 
    value = DateTime.Now; //Now it is DateTime  

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:

  1. Using Type dynamic - MSDN
  2. Access Office Interop Objects – MSDN
  3. Implicitly Typed Local Variables (C# Programming Guide)
  4. Dynamic Language Runtime Overview
  5. Massive: 400 Lines of Data Access Happiness
  6. StackOverflow dynamic vs var

1 Comments :

Anonymous said...

My cousin recommended this blog and she was totally right keep up the fantastic work!