Link

You can use ‘var’ all you want! Lets avoid it because it can be misleading and confusing. There is a difference between what var does in C# (implicit typing) and what beginners may think var does in C# (loose typing).

When we declare variables in Unity, almost always, they are explicitly typed. That means we are describing exactly what kind of variable it is.

int num = 10;

This is an Integer, because I used “int” to say as much. int num = “banana”; would throw a compiler error.

Every once in a while, somebody discovers on some example code that C# has a “var” keyword.

int num1 = 10;
var num2 = 20;

‘var’ in C# lets use implicitly typed variables. Everything is the same (this example, num2 becomes an int), but we don’t have to figure out the typing.

That looks similar to JavaScript, and is useful! Now you don’t have to remember what type your variable is, you can just declare it with var! Neat!

Problem is that the way Javascript and C# work are slightly different.

C# is still a “strongly typed” language, and variables declared with “var” will get turned into their appropriate types (as determined by the compiler). This is “implicitly typed” as opposed to “explicitly typed”. We just let the compiler figure that part out for us when we use var. The variable is still “strongly typed”.

JavaScript, on the other hand, is a “loosley-typed” language. It’s not the same thing as implicitly figuring out the what the type is, the compiler treats the variable differently. Read more about what those differences are here.

So … why don’t we use Var?

Clarity. In contexts where those learning Unity have come from other (loosely typed) languages, the use of ‘var’ can be misleading. C# is strongly typed, typing the variables ourselves never hurt anyone. Letting the compiler determine the type is a nice shortcut but makes example code harder to understand – the programmer still needs to know the type.

Letting the compiler choose the type can lead to some optimizations, there can technically be an small advantage there. Not a large enough one to listen to any dogmatic “you should always use var” proclamation, I believe understandable code is more important than these advantages.

To prevent confusion and make example code more readable, I don’t use ‘var’. A lot of C# programmers are unaware of var, and I don’t think the advantage is strong enough to be worth confusing them.

You, now knowing the differences between strongly-typed and weakly-typed languages, and between explicit and implicit typing, are now free to use var in your code all you want!

Read more in the C# documentation: