Geeks With Blogs
Kyle Burns

I’ve been putting a lot of thought lately into how LINQ can be introduced to programmers whose C# skills range from being a fairly new programmer conversant in C# to a seasoned programmer who learned just what they needed to convert skills in another language to C# and the .Net platform and I think that a workable approach would be to introduce first some of the concepts and language features that I view as existing to enable LINQ and then tie them together.  The first step we’ll take towards learning LINQ is to learn about the “var” keyword.

C# 3.0 added support for a feature called Implicitly Type Local Variables.  Put simply, this is when the type of a local variable declared within a method can be inferred by the compiler based on the expression used to initialize the variable.  For example, in the code:

   1:  string s = "this is my string";

we declare a string variable names s and initialize it with a string literal expression.  Using the var keyword to instruct the compiler to infer the variable type, the code can be rewritten as:
var s = "this is my string";

The rules around use of the var keyword are pretty straight-forward and really boil down to the need for you to provide the compiler with enough information for it to determine the intended type of the variable.  With this goal in mind, the rules are (from the C# 3.0 language specification):
    • The declarator must include an initializer
    • The initializer must be an expression.  The initializer cannot be an object or collection initializer by itself, but it can be a new expression that includes an object or collection initializer.
    • The compile-time type of the initializer expression cannot be the null type.
    • If the local variable declaration includes multiple declarators, the initializers must all have the same compile-time type

Here are some examples of where these rules are followed:

   1:  var result = true; // result is a bool
   2:  var i = 1, j = 2; // both i and j are int
   3:  var s = someObject.ToString(); // s is a string

and where they are not:

   1:  var s; // no initializer
   2:  var s = null; // initializer present, but can't infer type from null
   3:  var s = "1", i = 2; // can't mix types


Because one of my target audiences for this post if the classic VB developer that has migrated skills to .Net, it is important to note that use of “var” is nothing like the VB “variant” declaration.  With variant in VB, the type of the variable was unknown until runtime, so no strong type-checking could occur at compilation time.  With implicit typing, the type of the variable is known by the compiler and features like IntelliSense are still able to work.

Posted on Wednesday, December 7, 2011 8:25 AM | Back to top

Comments on this post: The Road To LINQ-dom Part 1–the var keyword

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Kyle Burns | Powered by: | Join free