When the var keyword was first added to the C# language many developers shyed away from it believing it to be a “Variant” type like found in VB.NET or the equivalent of declaring an variable as an object. Both of these are wrong, but despite this I’ve come across plenty of companies that still ban the use of var in their coding standards stating that it is not type safe.
The var keyword is completely type safe and is actually the equivalent of you typing the name of the type yourself but deciding it was easier to let the compier type the whole name for you. I find it better simply to look at the var keyword as a timesaver that instructs thecompiler that there is no reason for you to specify the type because: 1. anybody reading it can see the type immediately. 2. The exact type is unimportant as long as it meets the requirements of the code.
Its also worth pointing out at this stage that with modern IDEs I also consider the use of embedding type names into variable names using Hungarian notation or other similar approaches is also not only bad practice, but dangerous compared to proper use of DRY (Don’t Repeat Yourself) principles.
I use the var keyword all the time and find it makes code more readable, not less readable, especially when working with long type names.
For example line one here is much easier to read than line two. In fact in line two you have to search just to find the name of the variable.
Example 1
MyType hello = new MyType(); System.Collection.Generic.Dictionary<string, MyLibrary.Namespace.MyType2> goodbye = new System.Collection.Generic.Dictionary<string, MyLibrary.Namespace.MyType2>();
Using var both lines are equally easy to understand, and the name of both becomes the primary focus of the line rather than the type:
Example 2
var hello = new MyType(); var goodbye = new System.Collection.Generic.Dictionary<string, MyLibrary.Namespace.MyType2>();
Not to mention that you now have one less place to change if you decide to use MyType3 instead of MyType or MyType2 in this code block.
Using var on lines that already perform a cast can give similar readable and time saving advantages.
Example 3
var world = (Button)sender; var universe = sender as System.Windows.Form;
I also recommend using var for variables that are used to store results from methods where the type is unimportant either because we simply returning it or passing it to another method, or in the of enumerables, we have to specify the type name when we use it anyway.
Lets have another couple of real world examples:
Example 4
var value1 = GetValueFromDatabase(1); var value2 = GetValueFromDatabase(2); var value3 = Combine(value1, value2); return value3;
Reading the example alone you have no idea what type var is. This can upset some people, but if you are using Visual Studio its easy enough to mouse-over each “var” keyword to see the type that’s being used. But if you stop and think for a moment the reason you don’t know each type is because the current code doesn’t need to know. By practicing DRY here you’ve actually created code that’s much easier to maintain and is completely type safe. If in the future GetValueFromDatabase() was changed to return a decimal instead of an int it wouldn’t matter as long as Combine() had an overload that accepted decimals as parameters, or was changed at the same time. If we don’t use var then we would have to edit the code ourselves to switch value1, value2, and value3 from int to decimal, even though the changes has had no real affect on the current code block.
There are of course times when specifying the type explicitly over using var gives important extra information to the user then it should be used instead of var, but you will find these situations are few and far between. I might choose to use “int” for example if I was getting an int defined and returned from a method call in one line, but only if the fact I was performing some integer rather than floating point maths is important within the current code block. Otherwise I’m just making it hard to change the methods definition to work with double or decimal in the future.
Example 5
var form = new Form1(); var res = form1.ShowDialog(); if (res == DialogResult.Cancel) { // ... }
We’ve already talked here about why line 1 is good practice, but we’ve been “lazy” on line two and used “var” even though we have full knowledge that the return type will be System.Windows.Forms.DialogResult, and whats more that return type will never change as its part of the core .NET framework. Why is var useful in this context then? The better question is why actually would you “repeat” what you already know and specify later here anyway?
You and everybody else who is used to the System.Windows.Forms namespace knows the DialogResult type inside out. But what about people new to the toolkit, is the code still readable to them? I would argue that because we always specify the enumerable name on use, and the only purpose of the variable res is to be checked, specifying the type explicitly gains us nothing in readability, but does cost us more key presses.
I guess we can’t really say line 2 would “repeat yourself” in the same way as declaring a variable with both an explicit variable type and the new keyword on the same line, but we can say if we explicitly put the type on line 2 then we know we are planning to repeat ourselves on line 3, so here we are practicing Don’t Plan to Repeat Yourself to help us keep the DRY pricinple and keeping our code shorter by result.
If you’ve shed away from the var keyword yourself until now hopefully you are now inspired to give it a try and not just when your forced to using anon types and LINQ. You will find that when you follow the suggestions in this post your code will not only start to practice DRY but will actually increase in readability as the code you write become much more focused on the true dependencies and functionality of the method, and not the types your working with.
