2

With in the introduction of anonymous types in C# we got the var keyword.

Now people use var everywhere instead of the correct type. The reasons I've heard given for this are:

  • It makes refactoring easier
  • It's shorter
  • it improves readability

A common example might be

var result = client.GetResult(query);

is better than:

MyObject result = client.GetResult(query);

Because if you refactor GetResult to return a different object; for example:

MyOtherObject result = client.GetResult(query);

you don't have to also refactor the calling code.

However I recently had to do the following refactoring

IEnumerable<MyObject> GetResult(query)

to

Task<List<MyObject>> GetResult(query)

The calling code was along the lines of

//return true if there are any results
var result = client.GetResult(query);
if(result != null)
{
    return true;
}
return false;

Which after the refactoring would still compile and always return true. Whereas the explicitly typed form would have thrown a compilation error.

So. The question is. Given that there are downsides to using var instead of the explicitly typed variable. Is it simply a case of coding style preference, or are there clear reasons to use, or not use var in this fashion? (ie. other than where required with anonymous types)

Tulains Córdova
  • 39,570
  • 13
  • 100
  • 156
Ewan
  • 83,178

2 Answers2

9

FWIW I do find that var is overused. That doesn't mean it shouldn't be used though. These are the standards we use at my workplace.

  1. Use var when the type is obvious.

    var foo = new Foo();
    
  2. Don't use var when the return type isn't obvious.

    Foo foo = service.GetItem();
    
  3. Don't use var when the method returns a concrete type.

    ICollection<Foo> items = new List<Foo>();
    
RubberDuck
  • 9,021
2

As already stated , use of var is totally optional (other than declaring anonymous type). It is only a coding style preference.

I would use explicit type declaration when assigning value from a function. But it is only for the readability, not for the advantage if and when the calling function would be refactored.

The quoted example is indeed bad. Usually we'd perform an operation on the returned object. If there were some operations performed on the returned object from client.GetResult, definitely there would be a compilation error.

We don't normally return true or false after checking null. The called function can very well return true / false itself.
Or, as the return value before refactoring was IEnumerable<MyObject> the function client.GetResult could have returned an empty list (Null object pattern?) instead of null....just saying..

wonderbell
  • 722
  • 5
  • 7