Monday, March 31, 2008

var Variable

"var" is used to implicitly type a new variable. (Implicit simply means 'not directly stated'.)
Example:
var x = "Mark"; // Implicitly declared. 
string x = "Mark"; // Explicitly declared.
You will most likely never see the example above. So why do we need this?

C# 3.0 now is able to create and type classes on the fly. These new classes and properties of the class are instantiated and populated and assigned to a var variable.

Example:
var person = new { FirstName = "Mark", LastName = "Moeykens" }; 
string name = person.FirstName;
Here a new class is instantiated and assigned to the "person" variable. In this case it is impossible to explicitly state the type of the "person" variable.

Note: var variables cannot be public.

More Info: MSDN: var (C# Reference) Blog Post: Class and Collection Initializers