var vs dynamic keyword in C# 4.0




To put it as simple as possible, there is a simple difference between the C# ‘var’ and ‘dynamic’ keyword. When using the ‘var’ keyword, the type is decided by the compiler at compile time, whereas when using the ‘dynamic’ keyword, the type is decided by the runtime.

If you have been doing C# programming lately, you are already aware of the ‘var’ keyword, a strongly implicitly typed local variable for which the compiler is able to determine the type from the initialization expression - very useful when doing LINQ programming.

The ‘dynamic’ keyword was introduced in .NET 4.0 framework which also introduced the Dynamic Language Runtime (DLR) to accommodate dynamic languages like IronRuby and IronPython [are they dead?]. C# 4.0 provides access to this DLR using the new ‘dynamic’ keyword. C# is a statically typed language and the ‘dynamic' type automatically tells the compiler that it is a dynamic invocation, so ignore the compile time checking for this type. This also means that any invalid operations will only be detected at runtime.

Let’s see an example. Consider this piece of code:

var emp = new Employee();
emp.TakeBreak();


dynamic emp = new Employee();
emp.TakeBreak();

In the first case, i.e. when you are using the ‘var’ keyword, the type is statically inferred. So the line of code evaluates as

Employee emp = new Employee()


The compiler will check to see if a TakeBreak() method exists, if not, fail the compilation.

However that’s not the case when using the ‘dynamic’ type. Using the ‘dynamic’ type does not make it type-safe, hence the compiler is bypassed and the compiler does not check if the TakeBreak() method exists.

No type-safety? Why the hell do I need the ‘dynamic’ keyword for?

Well you need it because it is very useful in certain areas like interoperability. To start with an obvious one, it is very useful in dynamic languages that require runtime binding. Also, if you have an object declared as dynamic, then it’s no more your concern to handle how this object obtains it’s value. It’s value can be taken from a DOM object, or from a dynamic language like IronRuby, Reflection, Service or a COM API etc. The runtime takes care of the operations on this object.

The ‘dynamic’ type is also extremely useful when you are interoperating with Office Automation API’s. This saves you from casting everything from the object.

If you are interested, I will write a couple of more articles on the new ‘dynamic’ type and how you can use it to interoperate with the new Office Automation API’s. Let me know via the comments section if you care to see an example!



Will you give this article a +1 ? Thanks in advance




About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

13 Responses to "var vs dynamic keyword in C# 4.0"
  1. Anonymous said...
    September 5, 2010 at 12:45 PM

    Please do so.
    Thanks
    Sam

  2. Anonymous said...
    September 6, 2010 at 5:36 AM

    I'd also like to see some examples from real life projects of that new feature

  3. Anonymous said...
    September 6, 2010 at 8:53 AM

    Thanks - I would like to see how to use this to bind methods at run-time

  4. Anonymous said...
    September 6, 2010 at 10:33 PM

    yeah, it will help.

  5. Suprotim Agarwal said...
    September 7, 2010 at 4:17 AM

    Thanks all for your feedback. Watch out for an update on this post with an example, by the end of this week!

  6. Hunter said...
    November 14, 2010 at 2:13 PM

    Thank you very much for your blog. Outstanding.

    Yes, would love to see an office automation example

  7. Tanveer said...
    March 15, 2011 at 5:30 AM

    ya why not,will be great if post a tutorial or an example with WCF.

  8. Alex Ford said...
    April 9, 2011 at 12:29 AM

    More please.

  9. Hunter said...
    April 23, 2011 at 8:46 AM

    Thank you for the above.

    Yes, I would like to see more of this especially in an OBA context with VSTO or interop.

    Floyd

  10. Anonymous said...
    May 25, 2011 at 10:54 PM

    Very good example..please provide some example for how dynamic works..

  11. Anonymous said...
    December 28, 2011 at 8:46 PM

    gfewrwerwer

  12. Venkat Rao Tammineni said...
    November 20, 2012 at 9:15 PM

    Please come with more stuff...

    Thanks
    Venkat

  13. senthilstayss said...
    March 7, 2013 at 10:24 PM

    Nice one..

    Difference between Var and Dynamic in c#
    1. The Var(Implicit typed local variable) keyword is used to define local variables.In case of Var , the underlying data type is determined at compile time itself based on the initial assignment.Once the initial assignment has been made with Var type , then it will become strongly typed.If you try to store any incompatible value with the Var type it will result in compile time error.

    Example:

    Var strNameList=new List(); By using this statement we can store list of names in the string format.
    strNameList.add("Senthil");
    strNameList.add("Vignesh");

    strNameList.add(45); // This statement will cause the compile time error.

    But in Dynamic type, the underlying type is determined only at run time.Dynamic data type is not checked at compile time and also it is not strongly typed.We can assign any initial value for dynamic type and then it can be reassigned to any new value during its life time.

    Example:
    dynamic test="Senthil";
    Console.Writeline(test.GetType()) // System.String

    test=1222;
    Console.Writeline(test.GetType()) // System.Int32

    test=new List();
    Console.Writeline(test.GetType()) //System.Collections.Generic.List'1[System.String]

    It doesn't provide IntelliSense support also.It doesn't give better support when we give work with linq also.Because it doesn't support lambda expressions ,extension methods and anonymous methods.

    Check this blog for info about var and dynamic:-




    senthilvijayalakshmi.blogspot.in/2013/03/difference-between-var-and-dynamic.html

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions