Jul 5, 2010

Difference between var type of .NET 3.5 and object Data Type in .NET 2.0

With .NET 3.5 a new feature is introduced of defining Anonymous Type.
You can achieve this with keyword "var".

We can achieve the same functionality in .NET 2.0 with object type.

What is the difference between var type of .NET 3.5 and object Data Type in .NET 2.0?

var types are actually strongly typed in design time. What happens in the IDE infers the type of the object based on its initialisation so you get strong typing and intellisense
e.g.
var i = 99;
the IDE will pick up the i is an integer
using object you lose strong typing as all objects and primitive types inherit from object so you can potentially get runtime errors and type casting will give you a performance hit.



How var is strong type? The Value is assigned to var Variable at run time.

var is not assigned at runtime but design time that is why it is strongly typed.
Its type is inferred by the value that is initialised. That is why when you use VAR you need to declare and assign it in the one line

Another point is the difference of type casting. In object I have to type Cast explicitly and in case of var it's not required. is this correct?


You do not need to cast the VAR because it is strongly typed unlike object

No comments:

Post a Comment