Click here to Skip to main content
15,887,083 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Difference Between var and dynamic in C#

Rate me:
Please Sign up or sign in to vote.
4.83/5 (109 votes)
17 Jun 2013CPOL2 min read 373.5K   69   50
Difference between var and dynamic in C#

Introduction

The type keyword 'var' was introduced in C# 3.0 (.NET 3.5 with Visual Studio 2008) and the type 'dynamic' was introduced in C# 4.0 ( .NET 4.0 with Visual Studio 2010). Let us see the difference between these two.

Background

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 dynamic languages like Ruby and Python.

This means that dynamic declarations are resolved at run-time, var declarations are resolved at compile-time.

Table of Difference

var dynamic

Introduced in C# 3.0

Introduced in C# 4.0

Statically typed – This means the type of variable declared is decided by the compiler at compile time.

Dynamically typed - This means the type of variable declared is decided by the compiler at runtime time.

Need to initialize at the time of declaration.

e.g., var str=”I am a string”;

Looking at the value assigned to the variable str, the compiler will treat the variable str as string.

No need to initialize at the time of declaration.

e.g., dynamic str;

str=”I am a string”; //Works fine and compiles

str=2; //Works fine and compiles

Errors are caught at compile time.

Since the compiler knows about the type and the methods and properties of the type at the compile time itself

Errors are caught at runtime

Since the compiler comes to about the type and the methods and properties of the type at the run time.

Visual Studio shows intellisense since the type of variable assigned is known to compiler.

Intellisense is not available since the type and its related methods and properties can be known at run time only

 

e.g., var obj1;

will throw a compile error since the variable is not initialized. The compiler needs that this variable should be initialized so that it can infer a type from the value.

e.g., dynamic obj1;

will compile;

e.g. This code snippet of two statements -

{

var obj1=1;

obj1=”I am a string”;

}

will throw error since the compiler has already decided that the type of obj1 is System.Int32 when the value 1 was assigned to it. Now assigning a string value to it violates the type safety.

e.g. This code snippet of two statements -

{

dynamic obj1=1;

obj1=”I am a string”;

}

will compile and run since the compiler creates the type for obj1 as System.Int32 and then recreates the type as string when the value “I am a string” was assigned to it.

This code will work fine.

History

  • 17th September, 2012: Submitted the tip and trick

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
Software developer by profession, working for a service and product based organisation in India.

Career graph:
Software Programmer since 2002.
Web Developer in ASP.NET since 2004.

Interests:
I love reading the blogs and articles of technology experts. I love codeproject and stackoverflow .

I love to share knowledge and help the programmers. I appreciate if some body corrects my code or my concepts which helps me learn.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Paulo Morábito Neto12-Jun-13 6:50
professionalPaulo Morábito Neto12-Jun-13 6:50 
GeneralRe: My vote of 5 Pin
bbirajdar12-Jun-13 8:57
bbirajdar12-Jun-13 8:57 
GeneralGood Comparison Pin
Rajneesh Rai10-Jun-13 20:29
Rajneesh Rai10-Jun-13 20:29 
GeneralRe: Good Comparison Pin
bbirajdar12-Jun-13 8:58
bbirajdar12-Jun-13 8:58 
GeneralMy vote of 5 Pin
Renju Vinod29-May-13 0:05
professionalRenju Vinod29-May-13 0:05 
GeneralRe: My vote of 5 Pin
bbirajdar12-Jun-13 8:58
bbirajdar12-Jun-13 8:58 
GeneralMy vote of 3 Pin
Thanasis I.17-Sep-12 11:03
Thanasis I.17-Sep-12 11:03 
QuestionNot exactly right Pin
Thanasis I.17-Sep-12 11:02
Thanasis I.17-Sep-12 11:02 
"dynamic" is indeed a type. A clr type. "var" is NOT a type. There is no such thing as typeof(var). "var" is just a keyword of c# (i don't know about vb) that you can use in the left side of a variable initialization at the declaration of a local variable within a method. You can't even use it in a declaration of a class' field.

The purpose of var is
1) to save you from typing things like "MyLongNamedNamespace.MyLongNamedClass x = new MyLongNamedNamespace.MyLongNamedClass();".
In this case you can write "var x = new MyLongNamedNamespace.MyLongNamedClass();" and the compiler will produce the exactly same IL as the first statement. They are identical.

2) "var" comes in handy when you combine it with the c# 3 anonymous types and generics anonymous types are still clr types but you can't have the type name at coding time.

for instance let's assume you have a list of strings (List<string> sl) and you want to get a list of objects each one containing the string's first letter, and the string's length.
You can do that by

var result = sl.Select(item => new { FirstChar = item[0], Length = item.Length } );

now with this, you have a new list (result) that holds objects of the type that your lambda returns (the new {...} part). This type has no name. It is implicity declared by the compiler and given a name, you, the programmer don't know. So you can't explicity declare the type of "result". You can't say "List<..sometype..> result = ..." because you don't have this "sometype".
Here is where var comes in handy. You write "var result = ..." and you effectively tell the compiler "ok initialize a variable named result, with the value and type of the object the right hand of the initialization expression returns, whatever that may be, you are the boss you know it"

So var is not a type even if it looks like it's being used like one (which, in fact, is not true, since as I told before, you can't use var in a class' field declaration as opposed to using any other type).
SuggestionMy vote of 3 Pin
HeWillem17-Sep-12 2:46
HeWillem17-Sep-12 2:46 
GeneralRe: My vote of 3 Pin
bbirajdar17-Sep-12 3:03
bbirajdar17-Sep-12 3:03 
AnswerRe: My vote of 3 Pin
Christian Amado17-Sep-12 3:15
professionalChristian Amado17-Sep-12 3:15 
GeneralRe: My vote of 3 Pin
Lev Pavlas17-Sep-12 7:06
Lev Pavlas17-Sep-12 7:06 
GeneralRe: My vote of 3 Pin
HeWillem26-Sep-12 4:40
HeWillem26-Sep-12 4:40 
GeneralRe: My vote of 3 Pin
bbirajdar26-Sep-12 5:38
bbirajdar26-Sep-12 5:38 
GeneralRe: My vote of 3 Pin
johannesnestler17-Jun-13 4:26
johannesnestler17-Jun-13 4:26 
GeneralMy vote of 5 Pin
Christian Amado17-Sep-12 2:23
professionalChristian Amado17-Sep-12 2:23 
GeneralRe: My vote of 5 Pin
bbirajdar17-Sep-12 3:04
bbirajdar17-Sep-12 3:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.