Why woud i use var in C# ?


I’ve been usind C# for quite some time and i am usually defining my variables with their type.

Anyway i have recently watched some tutorials and the person, that explains them is using “var” to declare variables. Why is that? Is it good for some reason or it’s just a way to define a variable that you don’t know the type of, at the time of declaration? If so, does Unity re-declare it, when it knows the type? Coud that bring some errors…

For example this piece of code:

var vertColors = new Color[mesh.vertexCount];

		for (var i = 0; i < mesh.vertexCount; i++)
			vertColors *= color;*
  •  }*
  •  mesh.colors = vertColors;*
  •  mesh.RecalculateNormals();*

Why using var for declaring “vertColors”? And why isn’t Unity expecting to have “var[]” for declaring an array?
The first line can be also written like this:
Color[] vertColors = new Color[mesh.vertexCount];
but here Unity expects me to write [], after the type of the variable. Why it doesn’t give error, on the declaration (with var) above??
The tutor is also isung it to declare the “i” for the loop… I don’t get that at all…
So it seems that i can declare every type with var, instead of the type. Is that more expensive, than declaring the exact type?
As a whole, why woud i use var…
Thanks :slight_smile:

The var keyword still declares a typed variable and it only works when you immediately assign a value to to variable. It also only works for local variables in C#. So only inside methods and not for class variables. It has no advantanges and is just a shorter way to declare a local variable.

Since you have to assign a concrete type when the variable is created it’s usually clear what type it has.


var list = new List<GameObject>();

It’s especially handy for long generic type names:

var dict = new Dictionary<string, List<GameObject>>();
// it's equal to:
Dictionary<string, List<GameObject>> dict = new Dictionary<string, List<GameObject>>();

You should avoid using it where the type can’t be “seen” directly. Like:

List<MyCustomClass> SomeMethod()
    // ...

void Start()
    var list = SomeMethod(); // bad example, but also works.

In a lot IDEs (like Visual Studio) you can hover over the “var” keyword and it shows a popup with the inferred type.

About the Color array. Color[] is a completely different type than Color. Adding square brackets to a type defines a new type. An array type with the given element type. “var” just replaces any type, no matter which type. Again it’s just syntactical sugar. There’s absolutely no difference in the compiled code whether you use “var” or not.