Monday, 4 April 2016

Difference between VAR, DYNAMIC and OBJECT keyword


1. Stored Types:

    i)VAR:Can able to store any type of value but it require to initialize at the time of declaration.

    ii)DYNAMIC:Can able to store any type of the variable, similar to old VB language variable.

   iii)OBJECT:Can able to store any kind of value, because object is the base class of all type in .net  framework.

2. Information for Compiler:

    i)VAR: Its compiler safe i.e. compiler has all information about the stored value, so   that it doesn't cause any issue at run-time.

    ii)DYNAMIC: Compiler doesn't have any information about this type of variable.

   iii)OBJECT: Compiler has little information about the type.

3. Passing as Argument and Return Type for Functions:

   i)VAR: Var type cannot be passed as function argument and function can’t return Var type. This type variable can work in the scope where it defined.

    ii)DYNAMIC: Dynamic type can be passed as function argument and function also can  return object type.

   iii)OBJECT: Object type can be passed as function argument and function also can return object type.

4.Casting:

    i)VAR: No need to cast because compiler has all information to perform operation.

  ii)DYNAMIC: Casting is not require but you need to know the property and methods related to stored type.

   iii)OBJECT: Require to cast object variable to original type before using it. So this assigning to object type and converting to original type called as Boxing and Un-Boxing for value type and for the reference type its casting of types. It's actually increasing the overhead when we do this both operation. Allows to perform operation of given type once it get cast any user defined or primitive data type.

5.Causing Problem at Run Time:

    i)VAR: Doesn't cause problem because compiler has all info about stored value.

  ii)DYNAMIC: Cause problem if the wrong method or property accessed because all the information about stored value is get resolve only at run time.

   iii)OBJECT: Cause the problem at run time if the stored value is not get converted to underlying data type.

6.When to Use:

    i)VAR: Useful when getting result out of the linq queries. In 3.5 framework it introduce to support linq feature.

    ii)DYNAMIC: Useful when coding using reflection or dynamic language support or with the COM objects, because we require to write less amount of code.

   iii)OBJECT: Useful when doesn't have more information about the data type.



(Practice Makes a Man Perfect)

No comments: