1

Possible Duplicate:
Use of var keyword in C#

Which declaration should be accepted ?

var str = "Hi";

OR

string str = "Hi";

Even, my team lead always asks me to use 'var' when I iterate through collection using foreach, although the collection is typed one!

In C#, we usually declare variables explicitly. But I have a ReShaper installed and it prompts to change declaration from 'string' to 'var'. Is it a good practice? If yes, why?

Community
  • 1
  • 1
Learner
  • 4,661
  • 9
  • 56
  • 102

1 Answers1

2

This is a subjective/preferential question, and likely is a duplicate of others that have come before. I wouldn't be happy about ReSharper suggesting that everything should be declared as var.

Is it a good practice? Suggest that it's not super-relevant or there are bigger fish to fry in terms of good code. I'd suggest developer work or focus more on writing:

  • shorter/smaller methods.
  • well named variables and methods.
  • readable code. If this includes/excludes var

You can't avoid var when using anonymous types.

Readability is my chief concern. For declaring simple data types like string, int, ulong, I'd suggest that you're not really doing yourself any favours in terms of keystrokes or readability.

p.campbell
  • 98,673
  • 67
  • 256
  • 322