My current project has me writing C# scripts in Unity. Cool. I haven’t written C# for more than a decade. Today I was reviewing code, and noticed this line:
foreach (var child in Children)
Nothing too exciting. Readable. Easy to understand. But as I took a second look, I realized I didn’t truly know what var is all about. Is it defining a variable? What’s the type of child? Could var be replaced with ChildType? What’s best practice? Should I be using var?
Var was introduced in C# v3.0 circa 2007. It turns out it’s the equivalent to auto in C++, which I wrote about not long ago. Var allows the compiler to determine the type automatically.
So, var defines a variable. The type of var is the type that the compiler deduces. Var could be replaced with the actual type, but best practice is to use var whenever you can, just like auto. I’ll be using it regularly from now on.