Friday, November 19, 2010

"Var" Keyword

C# (.net 3.5) introduces a new var keyword that may be used in place of the type name when performing local variable declarations.  


the var keyword always generates a strongly typed variable reference.


Rather than require the developer to explicitly define the variable type, though, the var keyword instead tells the compiler to infer the type of the variable from the expression used to initialize the variable when it is first declared.


The var keyword can be used to reference any type in C# (meaning it can be used with both anonymous types and explictly declared types).


The easiest way to understand the var keyword is to look at a few examples of it using common explict types.  For example, I could use the var keyword like below to declare three variables:



The compiler will infer the type of the "name", "age" and "male" variables based on the type of their initial assignment value (in this case a string, an integer, and a boolean).


In addition to using built-in datatypes with the var keyword, you can obviously also use any custom types you define.  





Important: Although I'm using the "var" keyword above, I'm not using it with an anonymous type.  My LINQ query is still shaping the returned data using the "MyProduct" type.


Important Rule about the Var Keyword"-


Because the var keyword produces a strongly-typed variable declaration, the compiler needs to be able to infer the type to declare based on its usage.  This means that you need to always do an initial value assignment when declaring one. The compiler will produce a compiler error if you don't.






No comments:

Post a Comment

Note: Only a member of this blog may post a comment.