Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ReSharper want to use 'var' for everything? [duplicate]

I've just started using ReSharper with Visual Studio (after the many recommendations on SO). To try it out I opened up a recent ASP.NET MVC project. One of the first and most frequent things I've noticed it suggesting is to change most/all my explicit declarations to var instead. For example:

//From This:
MyObject foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
//To This:
var foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);

and so on, even with simple types such as int, bool, etc.

Why is this being recommended? I don't come from a computer science or .NET background, having "fallen into" .NET development recently, so I'd really like to understand what's going on and whether it's of benefit or not.

like image 765
Chris Avatar asked Oct 04 '22 20:10

Chris


People also ask

Should you always use var C#?

It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types. The complaint that var reduces readability is not shared by everyone.

Why should you use VAR?

var requires less typing. It also is shorter and easier to read, for instance, than Dictionary<int,IList> . var requires less code changes if the return type of a method call changes. You only have to change the method declaration, not every place it's used.

What can I use instead of VAR in C#?

Refactoring to replace var with an explicit type Use this refactoring to replace var in a local variable declaration with an explicit type. This refactoring applies to: C#

What is the point of Var in C#?

var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value.


2 Answers

What ReSharper suggests is clearly overuse of the var keyword. You can use it where the type is obvious:

var obj = new SomeObject();

If the type is not obvious, you should rather write it out:

SomeObject obj = DB.SomeClass.GetObject(42);
like image 297
Guffa Avatar answered Oct 17 '22 00:10

Guffa


One reason is improved readability. Which is better?

Dictionary<int, MyLongNamedObject> dictionary = new Dictionary<int, MyLongNamedObject>();

or

var dictionary = new Dictionary<int, MyLongNamedObject>();
like image 203
Mark Sherretta Avatar answered Oct 17 '22 02:10

Mark Sherretta