tags:

views:

117

answers:

5

Possible Duplicate:
Use of var keyword in C#

I don't really understand why you would the var keyword in C#

This code:

var s = "my string";

is the same as:

string s = "my string";

Why would you want to let the compiler determine the best type to use. Surely you should know what type to use. After all you are writing the code?

Isn't it clearer/cleaner to write the second piece code?

+1  A: 

See http://stackoverflow.com/questions/41479/use-of-var-keyword-in-c

Its very, very subjective!

Personally, I use "var" when I think its obvious what the type is, and I want to remove "noise" from the source code.

Matt Roberts
A: 

You use it because var is shorter than string and if you have an expression (especially a generic one) where the type is lengthy and unnecessary to type. The reality is that there's virtually no downside to using var as VS will pop up the type on mouseover of a variable name.

DeadMG
+1  A: 

It doesn't make much sense to me to use it there either. For some I can see more of a point just to save typing:

var cache = new Dictionary<int, Page>();

But even then I'd be tempted not to, as intellisense saves most of the typing anyway. For Linq, though, I pretty much always use it - you can determine the type, but this might change if you change the statement so it's a bit of a hassle.

Grant Crofton
+1  A: 
StringBuilder output = new StringBuilder();

becomes

var output = new StringBuilder();

Or anonymous types, ala LINQ:

List<MyClass> items = GetItems();
var itemsILike = items.Select(i => new { Cheeky = i.Monkey, Bum = i.Looker });

I used to use it more often, but now I try to avoid it for stuff like:

var items = GetItems();

For this example, though, it can still be useful if you're trying to work against code from another solution that you know is going to be refactored, but you still have to write code against.

Merlyn Morgan-Graham
A: 

To save typing and remove unnecessary codes, but use it only when it is obvious what type you are declaring

Louis Rhys