New Orcas Language Feature: Anonymous Types
page 4 of 10
by Scott Guthrie
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 36961/ 45

Understanding the Var Keyword

C# "Orcas" introduces a new var keyword that may be used in place of the type name when performing local variable declarations. 

A common misperception that people often have when first seeing the new var keyword is to think that it is a late-bound or un-typed variable reference (for example: a reference of type Object or a late-bound object like in Javascript).  This is incorrect -- the var keyword always generates a strongly typed variable reference.  Rather than require the developer to explicitly define the variable type, though, the var keyword instead tells the compiler to infer the type of the variable from the expression used to initialize the variable when it is first declared.

The var keyword can be used to reference any type in C# (meaning it can be used with both anonymous types and explictly declared types).  In fact, the easiest way to understand the var keyword is to look at a few examples of it using common explict types.  For example, I could use the var keyword like below to declare three variables:

Figure 3

The compiler will infer the type of the "name", "age" and "male" variables based on the type of their initial assignment value (in this case a string, an integer, and a boolean).  This means it will generate IL that is absolutely identical to the code below:

Figure 4

The CLR actually never knows that the var keyword is being used - from its perspective there is absolutely no difference between the above two code examples.  The first version is simply syntactic sugar provided by the compiler that saves the developer some keystrokes, and has the compiler do the work of inferring and declaring the type name.

In addition to using built-in datatypes with the var keyword, you can obviously also use any custom types you define.  For example, I could go back to the LINQ query projection I did in my previous blog post that used an explicit "MyProduct" type for the data-shaping and adapt it to use the var keyword like so:

Figure 5

Important: Although I'm using the "var" keyword above, I'm not using it with an anonymous type.  My LINQ query is still shaping the returned data using the "MyProduct" type - which means that the "var products" declaration is simply a shorthand for "IEnumerable<Product> products".  Likewise, the "var p" variable I defined within my foreach statement is simply shorthand for a a variable of type "MyProduct p". 


View Entire Article

User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 11:13:45 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search