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.
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
// Code size 14 (0xe)
.locals init ( string name,
 string name2)
IL_0001: ldstr "Compiler"
IL_0007: ldstr "Compiler"
} // 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
var x = null;
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. 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
- Are lock and Monitor the same in C#?
- Deep dive to async Main
- Extension methods – how they look like after compiling
- Anonymous types in C#
- C# and question marks
- IL perversions: throwing and catching strings