object vs dynamic vs var in C#

Object

  • It can store any kind of value because object is a base class of all type in .net framework.
    object obj;
  • object is not type safety.
  • object is initialize with null.
  • object type can be passed as method parameter and also can return object type.
    public object Method2(object param)
            {
                object objResponse = param;
                return objResponse;
            }
    
  • Casting required.

Dynamic

  • It can store any kind of value.
    dynamic obj;
  • dynamic is not type safety
  • dynamic is initialize with null
  • dynamic type can be passed as method parameter and also can return dynamic type.
    public dynamic Method2(dynamic param)
            {
                dynamic objResponse = param;
                return objResponse;
            }
    
  • Casting is not require but you need to know the property and methods related to stored type

Var

  • It can store any kind of value but it is mandatory to initialize at time of declaration.
    var obj=10;
    
  • var is type safety.
  • Can’t initialize with null
  • Can’t pass as method parameter and can not have return type as well
  • Casting is not required.

Tags: , , ,