Why when creating object it is preferred to use var keyword than real type?
var strList = new List<string>(); //good?
List<string> strList = new List<string>(); //why bad?
Question is not just about List<T>
.
Why when creating object it is preferred to use var keyword than real type?
var strList = new List<string>(); //good?
List<string> strList = new List<string>(); //why bad?
Question is not just about List<T>
.
The var keyword is great for hiding noise. When you have a statement like
List<string> strList = new List<string>();
you can be certain that strList is of type List. Typing the type twice is a waste of your time. If you decide to change the type later, you have to change it in both places.
My preference is to always use var when specifying the type is already obviously specified nearby. I often use var for any instance variable when the type is not of significant importance.
It is not that var
is good and the other one is bad. It's kind of personal preference.
If you want me to be more specific, I think you should use var
only when the type is completely evident, such as:
var employee = new Employee();
On the other side it's probably a horrible idea to do:
var e = GetEmployees();
Because it's hard to tell whether if e
is an Employee
object, or a List, array, etc.
Also is probably right to use it when it saves you some effort while not diminishing readability:
ReallyLongClassName someidentifier = new ReallyLongClassName();
VS
var explanatoryIdentifier = new ReallyLongClassName();
But at last, it comes down to be personal preference, just don't ever save you some characters if you are damaging readability.
It's just a good practice use List<string> strList = new List<string>();
(explicit typing). It makes the code more readable, but they are equivalent.
The argument for why var is good is that it removes the duplication of declaring the type. Meaning if you want to modify the type that strList (which is a bad name) is, you do it in one spot.