Why prefer var strList = new List<string>(); over List<string> strList = new List<string>();? [closed]

旧巷老猫 提交于 2019-12-10 22:24:59

问题


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>.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/15486589/why-prefer-var-strlist-new-liststring-over-liststring-strlist-new-lis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!