Are implicitly-typed variables the way forward (C#)
I am using StyleCop for Resharper on a project originally written for .net v2. But I've since upgraded this project for 3.5 framework.
Stylecop is recommending I change the bulk of my explicitly typed variables to implicitly typed for example:
string - var
custom开发者_Python百科 strong type - var
Is this the way forward when working with a .net 3.5 project. It seems unusual declaring everything as var.
Feel free to update the question title if my terminology is out...
Those are not generics, those are implicitly typed variables. This is really largely a matter of taste. There are places where you can overdo the use of var
and there are places where it's very clearly necessary (think anonymous types) so just find the place in the middle that suits your (and your team's) preference.
Been debated in many places, and it's down to taste. Compare these two lines of code:
StringBuilder stringBuilder = new StringBuilder();
var stringBuilder = new StringBuilder();
Which do you prefer?
Have a look at this
var (C# Reference) and
Implicitly Typed Local Variables (C# Programming Guide)
An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.
Also have a look at Use of var keyword in C#
and C# Debate: When Should You Use var?
I believe its more of a suggestion and should be considered, but not necessarily implemented fully.
While personal I believe the best use of var is when the declaring/returning type is obvious, i.e:
var temp = "Test me now";
versus
var temp = GetTestData();
Also I really enjoy being able to declare generic types with less code:
var test = new Dictionary<string,string>();
versus
Dictionary<string, string> test = new Dictionary<string,string>();
var is quite important when using e.g. anonymous types...
var cees = from c in Customers select new { c.Name, c.Birthdate };
Resharper will suggest to change all to var. For obvious definitions like
var c = new Customer();
I like to use it. for some API call I may write down the type explicitly:
Customer c = repository.Get(1);
精彩评论