• Register
262 points
‚óŹ3

Explanation of the type: var

  • In C# 3.0 or later, var type used for implicitly typed local variables and for anonymous types. The keyword var is often used with LINQ.
  • When a variable declared as a var type, the variable's type is specified from the initialization string at compile time.
  • It cannot be changed the type of var type variables at runtime. If the compiler can't specify the type, it throws a compilation error.
    class Program
    {
        static void Main()
        {
            var myInput = "Kodlogs";
            //Build Error: cannot implicity convert type 'int' to 'string'
            myInput = 100;
        }
    }
    

Explanation of the type: dynamic

  • In C# 4.0 or later, dynamic type used uses System.Object indirectly which is the root type in the C# class hierarchy.
  • it identifies the types at runtime only, so that it is not required explicit type casting for any operation at runtime.
  • It can be assigned with any type of data so that it's allocated memory location is dynamic and dynamic delays determination of the type until execution.
  • No casting required to performing valid operations on it.
    class Program
    {
        static void Main()
        {
            dynamic myInput = true;
            myInput = "Kodlogs";
            myInput = 100;
            myInput = myInput + " Kodlogs";
        }
    }

Explanation of the type: object

  • The root type in the C# class hierarchy, System.Object represented by the type object.
  • when we cannot specify the object type at compile time, which generally happens, when we deal with interoperability, then we use object type.
  • object requires explicit type conversion, cast to specified type before it can be used for performing an operation.
    class Program
    {
        static void Main()
        {
            object myInput = true;
            myInput = 100;
            //Build Error: Operator '+' cannot be applied to operands of type 'object' and 'int'
            myInput = myInput + 100;
            myInput = "Kodlogs";
            myInput = (int) myInput + 100;
        }
    }