Sunday, February 28, 2010

Var data type and C# typing

Var data type and C# typing

Release of C# 3.0 was blessed with the new keyword ‘Var’. Var allows you to declare a new variable, whose type is implicitly inferred from the expression used to initialize the variable.

Question is: Does Var affect the typing of the languages? Does C# version 3.0 is less statically typed than its previous versions?

Answer is No. Var does not affect the typing status of the language. C# still remains a statically typed language.

Let’s consider the below statement:

var x = "Sweet Var";

No errors are present in this statement.

Now, if we look at the definition of the dynamic type, it claims that In Dynamic Type, Values have type but Variables do not’.

So, don’t you think above statement, makes the Var declaration a good candidate for dynamic typing?

Well, the answer is No. Look at the below statement:

var x = "Sweet Var";

x = 1;

Error: Cannot implicitly convert type 'int' to 'string'

It means, compiler has the complete knowledge of the data type of the variable X (inferred from the type of value it has). So, above statement is nothing but a wrapper provided to a lazy developer (Not always. It has good usage for Anonymous types and many more), somewhat similar to the Extension Methods (a good candidate for my next blog J). So, I can assume how compiler will process the Var statement:

COMPILE: var x = "Sweet Var";

RAISE: GotALazyDeveloper(x, string);

REPLACE: (var x, String x)

COMPILE: Sting x = "Sweet Var";

1 comment:

  1. Dude.. are you not some years late in writing this blog.... ?

    Anyways.. I have seen people new to this "var" trying to use it like this:
    var x;
    and initialize it later..

    :P

    ReplyDelete