Tuesday 11 March 2014

Difference Between Var and Dynamic

Difference Between Var and Dynamic
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.
Var variable it doesn't associate the null with any type - not even Object

var                                                                                  Dynamic

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.
Introduced in C# 3.0
Introduced in C# 4.0
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. var obj1=1;
will compile
var 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.

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.







\

“Var” Keyword = Var keyword is an implicit way of defining DataTypes. Implicit means indirect way of defining variable types.

In simple words by looking the data at the right hands side the left hands side data types is defined by the compiler during the generation of the “IL” code.
Let me show a simple example what does implicit (indirect) way of defining DataTypes means.


In the above diagram you can clearly see that the variable “i” has directly define with the data type as “int” which is called as Explicit way of defining.
Now, let’s see how we can define data types in implicit (indirect) way.


In the above diagram you clearly see that how exactly you can declare variables using “Var” keyword which is also called as Implicit way of defining.

Note: - “Var” keyword defines data type statically and not on runtime.

Let me prove the above point with some practical demonstration so that you can get a better idea.
To see simple demonstration create a new console application for that just Go To > File > New > Project > Windows > Console Application.



Now just create a variable using “Var” keyword like below code snippet.
class Program
{
static void Main(string[] args)
{
var i = 123;
}
}
In the above code snippet I have declared a variable “i” using Var keyword and also assign value to it as “123” which means that the variable “i” will have data type as “int” as we have discussed earlier above.

Now, let’s try to add value as string to the variable “i” and try to compile the code and see that what the compiler has to say about it.
class Program
{
static void Main(string[] args)
{
var i = 123;
i = "Feroz";
}
}

In the above code snippet you can see that I have tried to add string value to the “i” variable and try to compile the code, the compiler throws an error like below diagram.


The above error diagram shows that cannot implicitly convert type ‘string’ to ‘int’ as the variable “i” is declared as “int” data type.

Let me prove the above point in one more way so that there is no confusion in your mind regarding the data type assigned to the variable “i” according to the value defined.


Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:
var i = 10; // implicitly typed
int i = 10; //explicitly typed

The following example shows two query expressions. In the first expression, the use of var is permitted but is not required, because the type of the query result can be stated explicitly as an IEnumerable<string>. However, in the second expression, var must be used because the result is a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. Note that in Example #2, the foreach iteration variable item must also be implicitly typed.
// Example #1: var is optional because 
// the select clause specifies a string 
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
                where word[0] == 'g'
                select word;

// Because each element in the sequence is a string,  
// not an anonymous type, var is optional here also. 
foreach (string s in wordQuery)
{
    Console.WriteLine(s);
}

// Example #2: var is required because 
// the select clause specifies an anonymous type 
var custQuery = from cust in customers
                where cust.City == "Phoenix" 
                select new { cust.Name, cust.Phone };

// var must be used because each item  
// in the sequence is an anonymous type 
foreach (var item in custQuery)
{
    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
}

dynamic (C# Reference)

Visual Studio 2013
2 out of 2 rated this helpful Rate this topic
The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The dynamic type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).
Type dynamic behaves like type object in most circumstances. However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.
The following example contrasts a variable of type dynamic to a variable of type object. To verify the type of each variable at compile time, place the mouse pointer over dynor obj in the WriteLine statements. IntelliSense shows dynamic for dyn and object for obj.
class Program
{
    static void Main(string[] args)
    {
        dynamic dyn = 1;
        object obj = 1;

        // Rest the mouse pointer over dyn and obj to see their 
        // types at compile time.
        System.Console.WriteLine(dyn.GetType());
        System.Console.WriteLine(obj.GetType());
    }
}
The WriteLine statements display the run-time types of dyn and obj. At that point, both have the same type, integer. The following output is produced:
System.Int32
System.Int32
To see the difference between dyn and obj at compile time, add the following two lines between the declarations and the WriteLine statements in the previous example.
dyn = dyn + 3;
obj = obj + 3;
A compiler error is reported for the attempted addition of an integer and an object in expression obj + 3. However, no error is reported for dyn + 3. The expression that contains dyn is not checked at compile time because the type of dyn is dynamic.

The dynamic keyword can appear directly or as a component of a constructed type in the following situations:
  • In declarations, as the type of a property, field, indexer, parameter, return value, local variable, or type constraint. The following class definition uses dynamic in several different declarations.
    class ExampleClass
    {
        // A dynamic field. 
        static dynamic field;
    
        // A dynamic property.
        dynamic prop { get; set; }
    
        // A dynamic return type and a dynamic parameter type. 
        public dynamic exampleMethod(dynamic d)
        {
            // A dynamic local variable.
            dynamic local = "Local variable";
            int two = 2;
    
            if (d is int)
            {
                return local;
            }
            else
            {
                return two;
            }
        }
    }
    
  • In explicit type conversions, as the target type of a conversion.
    static void convertToDynamic()
    {
        dynamic d;
        int i = 20;
        d = (dynamic)i;
        Console.WriteLine(d);
    
        string s = "Example string.";
        d = (dynamic)s;
        Console.WriteLine(d);
    
        DateTime dt = DateTime.Today;
        d = (dynamic)dt;
        Console.WriteLine(d);
    
    }
    // Results: 
    // 20 
    // Example string. 
    // 2/17/2009 9:12:00 AM
    
  • In any context where types serve as values, such as on the right side of an is operator or an as operator, or as the argument to typeof as part of a constructed type. For example, dynamic can be used in the following expressions.
    int i = 8;
    dynamic d;
    // With the is operator. 
    // The dynamic type behaves like object. The following 
    // expression returns true unless someVar has the value null. 
    if (someVar is dynamic) { }
    
    // With the as operator.
    d = i as dynamic;
    
    // With typeof, as part of a constructed type.
    Console.WriteLine(typeof(List<dynamic>));
    
    // The following statement causes a compiler error. 
    //Console.WriteLine(typeof(dynamic));
    

The following example uses dynamic in several declarations. The Main method also contrasts compile-time type checking with run-time type checking.
using System;

namespace DynamicExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            ExampleClass ec = new ExampleClass();
            Console.WriteLine(ec.exampleMethod(10));
            Console.WriteLine(ec.exampleMethod("value"));

            // The following line causes a compiler error because exampleMethod 
            // takes only one argument. 
            //Console.WriteLine(ec.exampleMethod(10, 4));

            dynamic dynamic_ec = new ExampleClass();
            Console.WriteLine(dynamic_ec.exampleMethod(10));

            // Because dynamic_ec is dynamic, the following call to exampleMethod 
            // with two arguments does not produce an error at compile time. 
            // However, itdoes cause a run-time error.  
            //Console.WriteLine(dynamic_ec.exampleMethod(10, 4));
        }
    }

    class ExampleClass
    {
        static dynamic field;
        dynamic prop { get; set; }

        public dynamic exampleMethod(dynamic d)
        {
            dynamic local = "Local variable";
            int two = 2;

            if (d is int)
            {
                return local;
            }
            else
            {
                return two;
            }
        }
    }
}
// Results: 
// Local variable 
// 2 
// Local variable
Dynamicvar gets processed in the compile time itself and shows any error during compile time itself.

dynamic gets processed in the runtime only and in case of errors it is hidden until runtime.

dynamic was introduced as part of the DLR (Dynamic Language Runtime) in .Net.

Example: 
dynamic d = new MyClass();
d.InexistingMethod();

Eventhough the method "InexistingMethod" is not there - it will get compiled and thrown exception in runtime.
var: 
1)It is a keyword that is used for implicit variable declaration 
ex: var a=100; 
var b="welcome"; 
The compiler determines the datatype of the variable declared with var keyword
on the basis of assigned value. we have to assign value with variable declaration
ex: var a;
a="welcome"; This is wrong 


2)var cannot be used to declare variables at class level. 
3)var cannot be used as the return type of methods. 
4)Intoduced in c# 3.0 

dynamic: 
1)It is a keyword used for variable declaration 

ex: dynamic a=100; 

dynamic b; 
b="good"; 

The datatype of the variable is determined at runtime 

2)dynamic can also be used to declare class level variables 

ex: class aa 

dynamic d; //correct 



3)dynamic can also be used as return type of the methods 

example: 

class dd 

static dynamic pp() 

dyanmic d; 
d=<some value>; 
return d; 


Var

The var type was introduced in C# 3.0. It is used for implicitly typed local variables and for anonymous types. The var keyword is generally used with LINQ. 

When we declare a variable as a var type, the variable's type is inferred from the initialization string at compile time. 

Object3.jpg

We cannot change the type of these variables at runtime. If the compiler can't infer the type, it produces a compilation error.

Object4.jpg

Dynamic

The dynamic type was introduced in C# 4.0. The dynamic type uses System.Object indirectly but it does not require explicit type casting for any operation at runtime, because it identifies the types at runtime only.

Object5.jpg

In the code above we are assigning various types of values in the variable amount because its type is dynamic and dynamic delays determination of the type until execution. All dynamic types variables enjoy the party at runtime.

4)Introduced in c# 4.0

3 comments: