C# – Will using ‘var’ affect performance

cperformancevarvariables

Earlier I asked a question about why I see so many examples use the varkeyword and got the answer that while it is only necessary for anonymous types, that it is used nonetheless to make writing code 'quicker'/easier and 'just because'.

Following this link ("C# 3.0 – Var Isn't Objec") I saw that var gets compiled down to the correct type in the IL (you will see it about midway down article).

My question is how much more, if any, IL code does using the var keyword take, and would it be even close to having a measurable level on the performance of the code if it was used everywhere?

Best Answer

There's no extra IL code for the var keyword: the resulting IL should be identical for non-anonymous types. If the compiler can't create that IL because it can't figure out what type you intended to use, you'll get a compiler error.

The only trick is that var will infer an exact type where you may have chosen an Interface or parent type if you were to set the type manually.