What is ‘Var?’
‘Var’ is a declaration of an ‘implicit type.’ This essentially means that the compiler knows what type you’re using without the need for you to declare it. The type is inferred based on the value. For example, if you added the code below:
var score = 2;
The compiler would infer that you are using an integer, and would treat it the same as if you had written the code below:
int score = 2;
If you changed the value of score to the string “two”, it would infer that the type is a string. The benefit of this is that you can change the value to one of a different type without the need to add a new type declaration.
Example Uses
Here are some other examples:
// Collections
var fooList = new List<string>();
// Complex Objects
var fooEmployee = new Employee();
// Linq
var britishCustomers = Customers.Where(x => x.Country == "United Kingdom");
Does the Use of ‘Var’ Decrease Performance?
There should be no performance difference between using implicit and explicit types. Under the hood, it’s going to be converted into the same IL code, so there’s no need to worry about affecting performance with the overuse of ‘var.’ However, there are some occasions (in my opinion) when you may want to skip it.
Readability is in my opinion, the key thing to consider when deciding whether to use ‘var’.
When Should I Avoid Using ‘Var?’
As with many programming paradigms, there’s no hard and fast rule dictating how you absolutely must use ‘var’, but here are some guidelines that I think act as a good basis when you’re thinking about how to declare your types.
Decide whether the type is likely to change in the near future
If the type is going to change, ‘var’ is useful, because if you change the type you wouldn’t need to alter the type. However, I think this is a bit of a false economy for one key reason, which brings me to my main rule around the use of ‘var,’ – Use it only if it is obvious from the type’s name, what the type represents.
If the Type is Obvious in the Name, Go For It
To follow the point above, while it’s great that we don’t have to change the declaring type if it changes, to follow this rule, you’d still have to change its name to make it clear what it represents. For example, if you have an array of integers called ‘numbers’ which then (for whatever reason) needs to change to a list of numbers, as long as you’ve named the type something descriptive like ‘numbers,’ I think using ‘var’ is fine. It’s only when it is unclear what the type represents that you should avoid ‘var.’
//examples of acceptable use of var
//obvious in the name of the type what it represents
var numbers = new List<int>() {1, 2, 3, 4};
var companyName = "Microsoft";
//obvious in the name what type is in use as well as what it represents
var decimalCost = 0.2;
On the other hand, if it isn’t obvious, then you need to be more explicit, and that means using the explicit type instead of ‘var.’ This way, it is super clear to any reader what type is in use.
// being more explicit
SalesEntity receipt = new SalesEntity();
CostMargin margin = CreateNewCostMargin(23.4565);
In the examples above, using var would remove certainty about the types in use, so by declaring the types explicitly, we keep things nice and clear. Readability is in my opinion, the key thing to consider when deciding whether to use ‘var’.
Convenience vs Readability
For some developers, it’s a style issue. For others, it’s just quicker for them to dump ‘var’ everywhere, and maybe this is fine if you’re quickly trying to validate an idea or prototype something. I think however it can turn into a dangerous habit. I’m a firm believer in ‘selfless code.’ Code which has been written with future readers in mind. So next time you’re unsure whether to use it or not, you can as yourself this simple question: ‘If I used ‘var’ instead of the concrete type declaration, would it be obvious?’ If the answer is yes, then by all means, get your ‘var’ on.
If you want to talk more about readability or using ‘var’, feel free to contact me, and if you enjoyed this post, feel free to subscribe to get more!
You can also find out more information about var direct from Microsoft here, as well as this great explanation from c-sharp corner.
In the “being more explicit” example using var would be perfectly acceptable, preferable even. For the simple reason that both the constructor and the create method clearly state what the type is.
Not using var actually creates less clear code here. Firstly it pushes the right hand side further over to the right and makes a sequence of declarations less likely to line up. Secondly there is unnecessary duplication of the type name which distracts when reading the code.
In my view var should be used virtualy everywhere, unless using C# 6 or later when the shortened form of constructors are available. Then it is often better to use
Foo foo = new();
than
var foo = new Foo();
particularly when the constructor takes parameters.
The entire sentence: “There should be no performance difference between using implicit and explicit types.” makes it look that the compiler is not discovering the real type of the variable when using implicit typing.
The typing (which is the thing that gets the performance difference) is there. So, it there is a performance difference, it isn’t because implicit and explicit cause a timing difference, it is because the implicit typing got it wrong.
And, honestly, that’s a much bigger issue.
The main use case for “var” in my opinion is when you are passing different types of data. like when you pass float and int interchangeably and then use the casting to the wanted type, which can let us conclude that while “var” let us not get stuck in writing a code when the variable type is nondeterministic, since the type should be determined on runtime (for the main use case it has) it most likely will result in a worse performance compared to predefined types.