What are Var and Dynamic keyword in C#?


Var keyword

  • Var keyword is used to declare implicitly type variables.
  • Syntax : Var i = 5 ; Value should be assigned at the time of declaration.
  • Var keyword is evaluated at compile time.
  • Once initialized with one data type value can’t be changed with another data type value.
    e.g; Var i = 5; i = “I am a Software Engineer”;
    It will throw an exception.

Dynamic Keyword

  • Dynamic keyword is used to declare implicitly type variables.
  • Syntax : dynamic i = 5 ; It is optional to assign value at the time of declaration.
  • Dynamic keyword is evaluated at run time.
  • Once initialized with one data type value can be changed with another data type value.
    e.g; dynamic i = 5; i = “I am a Software Engineer”;
    It will run successfully.

4 thoughts on “What are Var and Dynamic keyword in C#?

  1. R

    This needs a little fix, var should be dynamic in the second example:
    e.g; Var i = 5; i = “I am a Software Engineer”;

Comments are closed.