views:

356

answers:

5

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

+3  A: 

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?

David M
That one is obvious but when it comes to `var foo = 0m;` I'd be more careful.
Joey
Correct. And tools like ReSharper won't suggest var for that sort of declaration.
David M
+3  A: 

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.

Jason
+3  A: 

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?

astander
A: 

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>();
Pat
A: 

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);
flq