Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# var keyword usage [duplicate]

Tags:

c#

styles

Possible Duplicates:
What to use: var or object name type?
Use of var keyword in C#
What’s the point of the var keyword?
Should I always favour implictly typed local variables in C# 3.0?

I have just installed a trial version of ReSharper to evaluate it for my company. One thing that I have noticed is it is suggesting that I change the following (made up example):

string s = "";

to

var s = "";

Is it best practice to use the var keyword rather than using the Object Type when declaring variables? What advantages does it give. For context I am a former Java developer who has just transitioned to the .Net works.

like image 537
Jack Avatar asked Jul 30 '09 08:07

Jack


2 Answers

I think it's fine to use var where it makes the code easier to read, which for me would mean that the type that var is replacing must be completely obvious.

For example, this would be a good use of var (contrived example):

var thing = new Dictionary<int, KeyValuePair<string, int>>();

However this would be a bad use of var:

var thing = GetThingFromDatabase();
like image 63
Jon Grant Avatar answered Oct 20 '22 22:10

Jon Grant


I find it helpful in some cases where the type declaration is very long, for example:

Dictionary<int, string> item = new Dictionary<int, string>();

becomes

var item = new Dictionary<int, string>();
like image 34
CodeSpeaker Avatar answered Oct 20 '22 22:10

CodeSpeaker