Labels

Tuesday, April 29, 2008

Var Keyword - Orcas C# New Features

Hi,

This blog post summarizes the new features of C# langauge shipped with Orcas (VS 2005).

Below are the new features been introduced.

§ Automatic Properties

§ Object Initializers

§ Collection Initializers

§ Extension Methods

§ Lambda Expressions - p => expressions

§ Query Syntax

§ Anonymous Types

· Concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

· Particularly useful when querying and transforming/projecting/shaping data with LINQ.

§ Var Keyword


Var Keyword

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

For example, I could use the var keyword like below to declare three variables:

var name = "Arun";

var age = 30;

var male = true;

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:

string name = "Arun";

int age = 30;

bool male = true;

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 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.

The var keyword can be used to reference any type in C# - meaning it can be used with all three Explictly Declared Types [As above], Custom Types and Anonymous Types.

Explictly Declared Types: As Above.

Custom Types:

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, that uses an explicit "MyProduct" type for the data-shaping and adapt it to use the var keyword like so:

Anonymous Types:

Same as ‘Custom Types’ except when instantiating anonymous types you instead just leave the type-name blank after the "new" keyword:

Hope this helps.

Thanks & Regards,

Arun Manglick || Tech Lead

No comments:

Post a Comment