The Misunderstood var Keyword
I find amazing how the var keyword introduced in C# 3.0 is misunderstood.
The web is full of questions asking what are the performances implications of using var, of how var is not type safe and other completely false statements.
Also, one a day, I had a discussion with colleagues that argued that if I was using var, I could also use Object as the type for all the variables and then cast everywhere.
I don’t know why the var appears so misleading. I find it very simple, and have no issues using it a lot. Now, there are some readability discussion to using var, but that is purely subjective.
Everything Happens at Compile-Time
The very important concept that has to be understood is that with var, everything happens at compile time. You make the compiler work a little more when building your assembly, but the generated IL is exactly the same than if you explicitly use types.
So, the performances are only at compile time, and frankly, who cares of the performances at compile time?
Let’s go over this again.
Look at this code and the generated IL:
static void Main(string[] args) { String s = "Hello"; }
.method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 1 .locals init ( [0] string s) L_0000: nop L_0001: ldstr "Hello" L_0006: stloc.0 L_0007: ret }
Now the same code, using var instead of String:
static void Main(string[] args) { var s = "Hello"; }
.method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 1 .locals init ( [0] string s) L_0000: nop L_0001: ldstr "Hello" L_0006: stloc.0 L_0007: ret }
Exactly the same IL. Exactly.
To quote MSDN:
It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.
It cannot be more clear!
So please, stop picking on the poor var. Go pick on dynamic.
blog comments powered by Disqus