Friday, September 21, 2007

C# 3.0 - curtain raiser on var keyword

Hello readers, I'm going to start a series of blog posts here to get acquaintance with C# 3.0
Ok then, where to start?

Lets start with the “var” keyword. Perhaps that’s one of the most interesting thing in C# 3.0, So here we go,

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 -

[ datatype ] [ variablename ] = [ initializer ] ;

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 an implicitly typed local variables (or var for short) that instructs the compiler to infer the type of a local variable. For example:

var i = 1;

So, var i = 1; will result in creating a variable called "i", whose data type is "integer". It’s important to understand that this is still strongly typed. In a dynamic language, integer’s type could change later. To illustrate this, the following code does not compile:

var i = 1;
i = “hello atif”;

The C# compiler will report an error on the second line, stating that it can’t implicitly convert a string to an int.

Rather, this can be used as;

var i = “1”;
i = “hello atif”;

Now this time, var i, has become an string. This implies that var can be anything, from int to string or float or double, or even it can be some kind of object of classes or even table of datasets.

But then what is the difference between "var", "object" and "variant" (from COM or VB6 days)
Variants had issues regarding to occupy 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 or string - 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 "var" as follows –

var intArr = new[] {3,1,4,1,5} ;

Perhaps that has given u readers a clear word of what “var” is.


hit counter


1 comments:

shameel said...

great... nice article...

i believe this has cleared many things in my mind regarding var keyword..

keep it up !

Zubair Sheikh

Technology Evangelist Headline

Atif Siddiqui - Technology Evangelist

Search Results

Recent Tweets

    follow me on Twitter

    Comments