X

var keyword in C#

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";
    }
}

var keyword after compiling

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.

Wrapping up

So, I think now you believe me if I say that kayword var in C# is not same thing as var in PHP. But there’s more. By over-using var keyword it is easy to hide the actual types of variables and make it way harder for other developers to understand the code. Therefore it is good idea to use var keyword carefully.

More compiler secrets

Liked this post? Empower your friends by sharing it!
Categories: .NET

View Comments (9)

Related Post