C# Using Var: To Var or Not To Var?

C# var vs. explicitly typed

This can be one of those developer holy wars to avoid, but here is an opinion on this one.

Using var seems to be the rage today for reducing redundancy. Mostly, var is pretty benign or helpful, but perhaps it shouldn’t be used all the time, as there are possible problems that it could cause, even adding confusion or code misunderstandings in some cases, making code harder to read, or causing bugs.

One possible example of a problem scenario for using var (there could be more):

The only problem is var could hide the type in the code so that you don’t know what is returned, and the actions on the code could not work as expected.

Let’s Say You Wrote Your Own Type Comparison:

return 0 if equal, -1 if parameter 1 is less than parameter 2, 1 if parameter 2 is greater than parameter 1.

Let’s say GetValue originally looked like this:

You wrote code like:

In this case, if GetValue was modified either purposely or accidentally to return strings, the comparison would not compare correctly in all cases, but if int was returned from what was parsed, then it would compare correctly. 

If the code had instead been written as below using int instead of var, compilation would have failed if GetValue return value was changed to string:

You could say this isn’t something that would happen, but something very similar to this did happen with production code (it was VBScript, which had dynamic typing; in the above scenario, var acts somewhat like that, but instead allowing compilation to happen for something you might not have intended).

Summary:

I think it is safer to only use var when the types are obvious (or a few other scenarios that make sense).

Microsoft’s guidelines for var: (“C# Coding Conventions”—Microsoft Learn, n.d.)

Use var when it’s easy to tell the type of the variable being assigned.

You shouldn’t use var when it’s not easy to determine the type visually.

(Microsoft Reference: https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions).

My Recommendations for Guidelines for Var Usage:

  • Use var for anonymous types.
  • Use var with linq.
  • As Microsoft says, you can use var if the type is obvious. I say obvious means WITHOUT using IntelliSense (GitHub doesn’t have IntelliSense when reviewing code), with the caveat of if it makes things simpler; but if not, it shouldn’t be a requirement.
  • You “can” use var if the types are crazy complicated and muddle the code (though that is probably a smell itself and ideally avoided).
  • Use explicit types otherwise.

Reference Articles:

Some Other Viewpoints on Using Var:

Microsoft Coding Guidelines:

https://msdn.microsoft.com/en-us/library/ff926074.aspx

See other references here.

Hopefully that is enough evidence for you to make up your mind 😉

I hope you enjoyed the article.