var count = 1;
var output = "This is a string";
var employees = new EmployeesCollection();
In the above lines of code, the compiler sees the var keyword, looks at the assignment to count, and determines that it should be an Int32, then assigns 1 to it. When it sees that you assign a string to the output variable, it determines that output should be of type System.String. Same goes for employees collection object. As you would have guessed by now, var is a new keyword introduced in C# 3.0 that has a special meaning. var is used to signal the compiler that you are using the new Local Variable Type Inference feature in C# 3.0.
As an example, let us modify our string query example to use the var keyword.
private void btnLoopThroughStrings_Click(object sender, EventArgs e)
{
string[] names = {"John", "Peter", "Joe", "Patrick", "Donald", "Eric"};
var namesWithFiveCharacters =
from name in names
where name.Length < 5 select name' lstResults.Items.Clear(); foreach(var name in namesWithFiveCharacters) lstResults.Items.Add(name); } As the above code shows, the variable namesWithFiveCharacters now uses the type "var" instead of IEnumerable
If you run the code, it still produces the output.

No comments:
Post a Comment