Implicitly Typed Local Variables in C# 3.0 - The var Keyword
by David Hayden ( Sarasota Florida C# Web Developer ), Filed: C# 3.0 Tutorials
I am not sure the topic of Implicitly Typed Local Variables in C# 3.0 deserves its own post, but I am a sucker for the Single-Responsibility Principle and therefore couldn't convince myself to include it with its close relative: Anonymous Types in C# 3.0. I may have to join a support group for this Obsessive Compulsive Behavior :)
Here are my C# 3.0 Tutorials to date in no specific order:
Implicity Typed Local Variables in C# 3.0 aren't terribly exciting, but they are necessary for LINQ that creates anonymous types in queries for which you want to assign variables. However, Implicity Typed Local Variables aren't only used with LINQ, you can declare one easily as such:
var i = 5;
The var keyword is the key. When the compiler sees this in the code, it tries to figure out the type of the variable based on the value you assigned it. Hence, if you call GetType() on i, the type returned is actually System.Int32. The following will give you an error because the compiler can't figure out what type the variable is:
var i;
var i = null;
You have to initialize the variable with something that the compiler understands so it can figure out the type. Calling GetType() on firstName here would give you System.String:
var firstName = "David";
Of course, you hopefully won't be writing such code. You will mainly be using the var keyword and Implicitly Typed Local Variables with LINQ which creates anonymous types that you can't ( well don't is actually more correct as it is possible to create a custom type ) refer to during compile time. If you didn't have anonymous types and Implicity Typed Local Variables, you would have to define a custom type for each LINQ resultset.
List<Customer> listOfCustomers = new List<Customer> {
{ Id = 1, Name="Dave", City="Sarasota" },
{ Id = 2, Name="John", City="Tampa" },
{ Id = 3, Name="Abe", City="Miami" }
};
var query = from c in listOfCustomers
select new {FirstName = c.Name,c.City};
var customers = query.ToList();
Conclusion
Implicitly Typed Local Variables in C# 3.0 help you avoid having to define a custom type for each LINQ resultset.
News Feed: David Hayden ( Sarasota Florida C# Web Developer ), Filed: C# 3.0 Tutorials