protips

Logo

This site lists the protips that we shared with students during our courses

View the Project on GitHub appliedtechnology/protips

Prefer using the var keyword

C# is a statically typed language. This means, among other things, that each type needs to have a type when we declare it. For example:

string name = "Marcus";
Person marcus = new Person() { Name = "Marcus", Age = 49 };
List<Person> peopleList = new List<People>();
Task<List<VIPPerson>> vipPeopleListTask = getVIPPeopleFromDatabaseTask();

But since a long time C# supports using a keyword called var which gives the type an implicit type. Or in english: it will be typed, but we don’t need to care about declaring that type specifically.

Let’s rewrite the examples above using var:

var name = "Marcus";
var marcus = new Person() { Name = "Marcus", Age = 49 };
var peopleList = new List<People>();
var vipPeopleListTask = getVIPPeopleFromDatabaseTask();

Make no mistake, the variables still have a type, we just don’t have to specify them. For example, in your editor, hover over the name variable and you will see that it have a type. It cannot have any other type, since it’s been assigned a string "Marcus". If I wrote var name = 49; name would have been an int.

At first glance we can see that the code is shorter and there’s a lot of cruft being removed (and some repetition).

But there’s a hidden point here too that I think is important when it comes to code readability; in most cases we don’t need to know which type it is to use it. We can lean into the tooling to help us to get errors for if we pass the wrong thing to methods expecting other types.

Also, notice the last line, as an example for when this becomes really important: var vipPeopleListTask = getVIPPeopleFromDatabaseTask();. We are probably using going to await that task. We don’t really need to care that it is a Task<List<VIPPerson>>. Right now I just care that I have task to get a VIP People list. That type is declared on the getVIPPeopleFromDatabaseTask method and I can look it up later.

Using var also pushes me to name variables better since the name of the variable is really the only thing I have left to communicate my intentions with.

Recommendation

Extras

Nullable types with var

There’s one little subtle feature of using var that can be good to know: var creates a nullable type. See this example:

string name = "Marcus";
var name2 = "Marcus";

name2 = null;
name = null; // breaks

By using var it is like you would write string name? = "Marcus";. Pretty nifty to know.

Debate … no more

There used to be a debate over the merits of the var-keyword and it’s usage, but that debate is mainly died out and now people generally seems to prefer var whenever the can.

If you want to read some arguments pro and con go here https://www.infoq.com/news/2008/05/CSharp-var/