Wednesday, December 09, 2015

Implicit typing in C# using "var"

I use the var keyword everywhere. Someone told me today that this is a bad practice, because "sometimes you can't tell what type it is".

Well, I disagree. I believe we generally don't care what type a variable is, we care about how we use it, the interface it provides to the programmer. For example:
foreach(var i in myListOfThings) {
I don't care what typeof(i) is, I just want to know it has a .name attribute. If I change the type later, I probably still want it to have a .name attribute, and the var keyword lets this code keep working. Also:
var v = new Vector3(0,0,0);
Vector3 v = new Vector3(0,0,0);
In this case, the Vector3 type declaration is redundant, it is simply repeating information already on the same line. Remember, repeating yourself in code is a Bad Thing. Later on if I realise my Vector3 variables need to be Vector2 variables, I need to change the type information in 2 places for each variable. Yuck.

Finally, var lets me write less characters, which often means less backspacing and retyping!
var now = System.DateTime.Now;
System.DateTime now = System.DateTime.Now;

This well written post describing more advantages of implicit typing. To Summarise:
  • It induces better naming for local variables.
  • It induces better API.
  • It induces variable initialisation.
  • It removes code noise.
  • It doesn't require the using directive.

Popular Posts