Var keyword in orcas

June 17, 2007

What is it??
As the name suggests, “var” keyword can be used in place of type name in local variable declarations.

Is it a untyped variable reference??
No, it is not a late bound or untyped variable reference. It always creates a strongly typed variable reference. When the var type variable is declared, the compiler infers the type of the variable from expression used to initialize the variable when it is first declared. for example, var name = “yoganand”; will be inferred as string name=”yoganand”;.The CLR actually never knows that the var keyword is being used – from its perspective there is absolutely no difference between the above two declarations but in the first declaration, the compiler does the work of inferring and declaring the type name.

What types can be referenced with var keyword??
Var keyword can be used to reference any type(anonymous and explicitly declared types) in C#.
Even custom types we define can be referenced.Var keyword produces strongly typed declarations and hence the compiler needs to be able to infer the type based on its usage. So, var definition should always be initialized, produces a compiler error otherwise.

Leave a Reply