views:

143

answers:

2

I just started using Resharper. One of its features is that it suggests changes to the code based on, i suppose, good coding practices.

One of the changes it suggested is to change the variable type to var during assignment. I kept on changing and now the code has var everywhere. Somehow I get the feeling that "var" keyword makes the code a bit difficult to understand.

Is it a good coding practice to use "var" whereever possible or is it better to stick with the actual type. (except anonymous types where its required to use "var")

Thanks.

+1  A: 

The C# programming guide suggest using var when it enhances readability, for instance when the type is obvious, too complicated or not important at all.

The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code. One example where var is helpful in this manner is with nested generic types such as those used with group operations. In the following query, the type of the query variable is IEnumerable<IGrouping<string, Student>>. As long as you and others who must maintain your code understand this, there is no problem with using implicit typing for convenience and brevity.

There is no general rule. There are situations where the explicit type may enhance readability.

Examples:

var x = new Thingy(); //type is obvious

var x = dict.Where(x => x.Value > 3); // type is complex and not important

Foo(GetValue(FromOverThere())); // type aren't implicit anyway

// equivalent to:
var fromOverThere = FromOverThere();
var value = GetValue(fromOverThere)
Foo(value);

FooDocument doc = repository.Get(id); // glad to see the type here.
Stefan Steinegger
+1  A: 

I suggest using var when you have code like this:

var surelyAnXText = new XText(...);

where you always can tell the want type we are declaring a variable of. But not when you have something like this:

var whatIsThis = foo.Some_Method_Where_You_Cant_Tell_The_Return_Type_From_The_Name();
lasseespeholt