Silly Arguments: Var vs Not to Var

Previously, we have discussed the silly arguments of tabs versus spaces, squash versus no-squash merges, and constructor injection versus service locator.

Now it’s time to talk about var.

When I first found var in .NET 3.5 SP1, I thought they had ruined .NET.

This wasn’t the first time I thought they had ruined .NET. The first time was with generics in .NET 2.0. I had experienced templates in C++, and was worried what they would do to C#, but generics in C# were amazing. I use them a good amount today, and I wouldn’t want C# without them. I was also concerned about .NET Core at one point, but I am warming up to it too.

Back to var.

Var is a way to declare a variable without specifying the type. It is also statically and strongly typed, just like you used the variable name.

Example
Customer customer = new Customer();
Becomes
var customer = new Customer();

Now in that example, the first Customer is irrelevant. You can determine that by the type created with New Customer(). There isn’t more information being included by the first Customer. Over time, I became comfortable with the var customer = new Customer() option.

I prefer var for almost everything, which is where I feel many C# people have ended, including John Skeet. You can listen to him discuss this in the .NET Rocks episode #1521. I might not use a var only if I feel adding the type is really adding to the readability, which doesn’t happen that often.

Where is the conflict?

Customer customer = customerAccessor.Find(1);
Vs
var customer = customerAccessor.Find(1);

Most C# developers prefer the first option as it makes it obvious that a customer is being returned. I prefer the second because I don’t feel the Customer type on the customer variable helps. When I read the line of code, I see we are calling the Find method on the customerAccessor and am pretty sure I know what is coming back. And if not, I can F12 on the var. Other developers prefer the explicitness of Customer to denote the type.

In closing, please stop worrying and love the var.


Related posts