Meta

C# Implicitly Typed Local Variables Internals

OK, so most .NET coders are aware that C# >= 3.0 offers the ‘var’ keyword to provide implicitly typed local variables. One thing that intrigues me is just how this is achieved, and is their there any performance loss/gain by choosing this method ?

Now the obvious thing that you will notice about this program when it’s run, is that the trend of generic vs non-generic timings are the same (i.e. there is no great difference between using C# ‘var’ keyword or not, even when comparing to boxing and non-boxing types).

The definitive answer to how this works can be found with our friendly tool ildasm.

Even with no understanding of ilasm, you can see with the disassembly of our Main() static function that the local variables types declared for both our ‘var var_ngc’ and ‘nongeneric_class ngc’ variables are exactly the same. The same goes for our ‘var var_gc’ and ‘generic_class gc’ types.

All the C# compiler is actually doing is substituting the ‘var’ keyword for the apropriate variable type… disappointing. Unfortunately there is no magic here 😦