Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between var and dynamic in C#

    • 0
    • 2
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 59
    Comment on it

    "Difference between var and dynamic in C#"

        To understand the differences more clearly, let us go through the following table:

    VAR DYNAMIC
    This was introduced in C# 3.0 This was introduced in C# 4.0
    In this the variable type is decided at compile time only. Therefore it is called Statically typed . In this the variable type is decided at run time.Therefore it is called Dynamically typed .
    It has to be initialized at the time of declaration. No need to initialize at the time of declaration.
    In this since the variable type is known at the compile time therefore the Errors are caught at Compile time itself. In this since the variable type is not known at the compile time therefore the Errors are caught at Run time.
    In this intellisense is shown by the Visual Studio, as the type of variable is known by the Compiler. As the variable type is not known by the Compiler therefore no intellisense is shown.
    Example:
    var obj = "Welcome";
    As per the value assigned to the variable 'obj' the Compiler will treat the variable 'obj' as a string.
    Example:
    dynamic obj;
    In this no need for initialization as the type of variable will be decided at run time.
    Example:
    var obj;
    This will throw an error as it has to be initialized at the time of declaration so that the Compiler can decide the variable type.
    Example:
    dynamic obj;
    This will work fine.
    Example:
    var obj = 1;
    var obj = "Welcome";
    This will give an error as the Compiler has decided that the variable 'obj' is of type Int,as per the first declaration. But again assigning the string to it will violate the type safety.
    Example:
    dynamic obj=1;
    dynamic obj = "Welcome";
    This will work fine as the variable type is decided at the run time therefore the Compiler first creates the type of 'obj' to Int and then recreates it to string when string is assigned to it.
    It cannot be passed as method argument, it works in the scope where it is defined. It can be passed as method arguments.

    Happy Coding..!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: