Sunday, January 20, 2008

Demystifying C# 3.0 - Part 1: Implicitly Typed Local Variables "var"

Demystifying C# 3.0 - Part 1: Implicitly Typed Local Variables "var"
A 5 minute a day;digestable blog series.
Posted on 6/30/2006 @ 8:40 PM in #Vanilla .NET 8 comments 5407 views
I am going to publish a series of blogposts that intend to bring C# 3.0 down to earth. C# 3.0, along with LINQ, and all the heavy duty talk that surrounds it has sort of made it difficult to understand IMO. Well - if not difficult to understand, it sure is tough to gauge - "Where to begin".So with 5 minutes a day, a short post a day will dice and slice a single feature, and we will logically move to a fuller picture of C# 3.0, followed by LINQ, and DLINQ (if I still have steam left).So here we go, with the first in that series, the "var" keyword.In C# 2.0, you can declare an integer (or anything for that matter of fact) as - int i;You could also write something like - int i = 1;Generally speaking - = ;Okay good. The important thing to realize is that "i" is an integer. In C# 3.0, the below is a valid statement - var i = 1;But what is "var"? "var" is .. umm .. a keyword, that results in "i" being of the same data type, of the initializer ~ in this case an integer. So, var i = 1; will result in creating a variable called "i", whose data type is "integer".But then what is the difference between "var", "object" and "variant" (from COM or VB6 days).Variants were oink oink piggies, basically a catch all pig that occupied way too much memory. Objects have boxing unboxing issues. Both Variants and Objects are not strongly typed.Note that "i" is strongly typed to an integer—it is not an object or a VB6 variant, nor does it carry the overhead of an object or a variant. To ensure the strongly typed nature of the variable that is declared with the var keyword, C# 3.0 requires that you put the assignment (initializer) on the same line as the declaration (declarator). Also, the initializer has to be an expression, not an object or collection initializer, and it cannot be null. If multiple declarators exist on the same variable, they must all evaluate to the same type at compile time.You could also create "arrays" of "vars" as follows - var intArr = new[] {3,1,4,1,5} ;Great !!! I hope this clarifies a bit what "var" is, in my next post, we will see what "Anonymous Types" are.

Labels: , , ,


Post a Comment

Subscribe to Post Comments [Atom]

<< Home