When to use or not to use var in C#

The var keyword let you declare a local variable implicit. During compilation, the type of the variable is determined. It allows you to quickly define a variable, where the type of the variable is trivial. Using the var keyword can lead to some discussion when code guidelines are made up, since some people say it makes programming easier but people may also argue that code is less readable.

First of all var is not allowed in global class variables or parameters of methods, only local variables where they also must be initialized. Var variables cannot be initialized to null, a method group or an anonymous function. Var is introduced in C# 3.0, mainly to support anonymous types which are needed for LINQ. Think of

var users = new { Name = "John" , Surname = "Doe" }
My guideline when to use var-keyword is only this one: When it’s trivial which type you get after initialization. For example:
var userList = new List<Users>();
It is trivial that you have here some list, which contains… users. Please don’t use it in this way:
var user = Database.GetAllUsers()
since it’s not sure what kind of type GetAllUsers will return.
Some people like to use var, since they say Intellisense can determine what the type of variable is. However, this doesn’t make your code easier to read. Then you have to depend on tools like Intellisense or even Resharper. The later likes to transform each local variable into a var.
My opinion: use it wise when the result type is trivial. Otherwise just use the type of your instance when you declare the variable.
Posted in Best practices, C# by Bruno at June 25th, 2015.

Leave a Reply