Gunnar Peipman's ASP.NET blog

C# and var keyword

C# 3.0 introduced us new language feature: type inference using keyword var. Some guys think that var in C# is same thing as var in PHP. That's wrong - var keyword in C# is totally different thing and it doesn't mean that C# has now support for type changing class attributes. Let's prove it.

I will use very simple example code here but it makes the point perfectly clear later. So here's the code.


class Program
{
    static void Main(string[] args)
    {
        string name = "Compilers";
        var name2 = "Compilers";
    }
}

Now let's see what happen if we compile this code. If var doesn't mean type inference and it is therefore something different then compiler doesn't produce two analogous code blocks for variables we declared. Compiler creates the following IL code.


.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       14 (0xe)
  .maxstack  1
  .locals init ([0] string name,
           [1] string name2)
  IL_0000:  nop
  IL_0001:  ldstr      "Compiler"
  IL_0006:  stloc.0
  IL_0007:  ldstr      "Compiler"
  IL_000c:  stloc.1
  IL_000d:  ret
} // end of method Program::Main

If we look at this code we will see that there are two local variables declared as string: name and name2. These are the same variabled we declared before. So their types are correct. If we look at the code where assignments are made we can see that these assignments are very similiar, so there is no additional activities made in the case of variable declared with keyword var.

If we try to compile something like this


void SomeMethod()
{
    var x = null;
    var y;
}

we will get errors because on first line we are using null and null has no type. Second line gives error because there is no type specified and therefore there is nothing to infere.

So, I think now you believe me if I say that kayword var in C# is not same thing as var in PHP :)

Comments

Bharath Reddy VasiReddy said:

Thats nice stuff to read. Thankyou.

Thanks

Bharath Reddy VasiReddy

# June 24, 2008 4:26 PM

Gunnar Peipman's ASP.NET blog said:

Keyword var is cool thing we can use to make our code more readable for other programmers and why not

# July 12, 2008 12:55 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)