C# developers usually love the keyword var:

var isProcessed = false;
var numberOfElements = 10;
for (var i = 0; i < productList.Count; i++)
    // ...

How can this innocent keyword be bad?

Let's see.

var queryResult = customerService.FindByIdentifiersWithDirectAssociates(identifiers);
var whatTheHack = (
                       from e in queryResult
                       where e.Catalogs != null && e.Catalogs.Count > 0
                       select new {Identifier = e.Identifier, Catalogs = e.Catalogs}
                   ).ToLookup(e => e.Identifier, e => e.Catalogs);

What does this Lookup contain? Reading code should be easy, right? Here we struggle. var prevents us from understanding the code without waiting for tooltips to popup or jumping to class CustomerService.

When writing code, keep in mind that no one knows all the system's types, methods, and used APIs. Even the author herself might forget what var is standing for during the three month after writing those lines. Although your IDE might recommend var all the time, think about whether or not it makes sense not to use it. When you're calling another method, is it really clear what that method returns? Don't think the variable's name tells it all. A var customerList might be a IList<Customer>, IList<CustomerDTO>, IList<object[]>, or something else. Your code should be clear, even in printed form. Use var intentionally, not just because you always use it.

  • Use it when you're declaring a variable of a simple type and initialize it with a constant value
  • Use it when creating an object with new straight away
  • Use it with care when calling other methods, no matter whether of the same class or another
  • Don't use it when using complex LINQ expressions (if you have to use var because your LINQ expression returns an anonymous type, carefully explain what you're doing with a comment)

This is the same code without var:

IEnumerable<Customer> queryResult = customerService.FindByIdentifiersWithDirectAssociates(identifiers);
ILookup<longIList<string>> whatTheHack = 
(         from e in queryResult         where e.Catalogs != null && e.Catalogs.Count > 0         select new {Identifier = e.Identifier, Catalogs = e.Catalogs}     ).ToLookup(e => e.Identifier, e => e.Catalogs);

It's obvious this code still does need some comments to tell its story, but in my eyes this is much better.


About me

Jack of all trades, husband, father, software engineer.