Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var versus concrete type usage [duplicate]

Tags:

I have checked 5 or more post in stackoverflow regarding var usage but I am still looking for an answer regarding var usage. I am used to use Concrete type instead of var, but my Resharper complains to change to var. Is var a choice of type - even when concrete type is known?

like image 782
KrishnaDhungana Avatar asked Dec 05 '13 05:12

KrishnaDhungana


People also ask

Is using var better?

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 is the difference between VAR and object?

The object type can be passed as a method argument and method also can return object type. Var type cannot be passed as a method argument and method cannot return object type. Var type work in the scope where it defined. Dynamic type can be passed as a method argument and method also can return dynamic type.


1 Answers

The following is an extract from msdn...

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

However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.

Reference: http://msdn.microsoft.com/en-us/library/bb384061.aspx

Good Luck!

like image 199
gpmurthy Avatar answered Oct 26 '22 23:10

gpmurthy