About the author

Vijay Kodali
E-mail me Send mail

Recent comments



The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2024

Implicitly Typed Local Variables-“Var”

In C# 3.0, you can declare an integer  as –


var first = 7;

Console.WriteLine("First variable is of type: {0}", first.GetType());


It will return”Int32” as DateType, even though we declare it as “var”. So what  is “var”?

from MSDN..

Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

To put it simply "var" is a keyword that results in variable being of the same data type, of the initializer. It works similar to “object” type in older version. But there is great difference between “Object” and “var”. Check following code snippet-


object newObj = 58;  

int test = newObj; //this line result in an error "Cannot implicitly convert type object to int"

 int test = (int)newObj; // this line will work. But result in boxing..additional overhead


So Objects have boxing and unboxing issues. Now consider same instance with “var”- 


var newObj = 22;

int test = newObj; //no boxing involved. It is type-safe


C# is still strongly typed. “Var” is NOT a variant, everything is known by the compiler at compile-time.

Posted by vijay on Friday, January 18, 2008 9:11 PM
Permalink | Comments (0) | Post RSSRSS comment feed