tags:

views:

433

answers:

11

Just curious. I'm about 99.999% sure there is none...but anything?

EDIT: These are OK answers (saving typing time or making the code less verbose for "readability"). I guess I should have clarified what I meant by "use" - some construct/design that couldn't be done without "var" .

+3  A: 

I use var all the time-- especially when the class name is very long.

It doesn't post a problem for me because my methods are usually named in such a way that by just taking a glance of the name, I can infer the type.

And if I can't, I will use the VS 2008 intellisense to help me, or I just use Resharper var=> class name converter to convert it to the explicit name.

Another case I find a great use of var is in a foreach loop:

foreach(var id in idList)
{
  // do what you will here
}
Ngu Soon Hui
nothing like long class names to ruin your day... `TableLayoutPanel` and `TableLayoutPanelCellPosition` almost rotted my hands off back in the day
STW
+21  A: 

Whats better in terms of readability?

AReallyReallyLongBusinessObjectName obj = new AReallyReallyLongBusinessObjectName();

OR

var obj = new AReallyReallyLongBusinessObjectName();

I say in terms of readability because using var has absolutely no impact on your app seeing as the two statements generate the same IL when compiled.

Response to edit: there is nothing that requires you to use var (other than anon types) - its just syntactic sugar.

Darko Z
Even more so when using generic types.
Ty
i guessed as much(syntactic sugar). how would one write the code below without var, though?-------var subset = from i in numbers where ....foreach (var i in subset){---
moogs
assuming numbers contains ints then you'd do this: IEnumerable<int> subset = from....
Darko Z
oh and second part foreach(int i in subset)....
Darko Z
right! i was looking in the wrong direction looking for a WhereArrayIterator class. Thanks!
moogs
This is an indication that your design and naming is wrong, not that you should use `var`.
Noon Silk
That may be so, but I'm not saying you *should* use var, rather I'm giving an example of better readability by using var. In any case I would argue that for whatever the objects class name is, instantiating it in a var is more readable.
Darko Z
Dan Herbert
+1  A: 

Yes, I use it all the time while creating objects for class with long name and in foreach loop

EDIT : I don't think var could play major role in design or in any construct... because it can only be used in locally i.e within method or in scope.

Another major restriction of var is you can not use it as method parameter or as a return type. You even can not declare it as field in class. It means we can use var just to save typing time or making the code less verbose for "readability" and with LINQ

Prashant
+14  A: 

I use it in foreach loops very often:

foreach(var item in collection)
Scott Dorman
You can use var for linq? This is pretty much the only way I use it.
Spence
@Spence: You can use `var` for anonymous types which commonly arise when using LINQ.
Jason
Satire is very difficult to project in a forum. Cheers for the tip ;)
Spence
This is very annoying, as it is not obvious that the type that `item` is. Really do not recommend this approach.
Noon Silk
in a simple scope this is completely okay. and since we keep close to the single responsibility principle, every method IS a simple scope ;-)
Marc Wittke
It's perfectly valid and it saves you from the exception: http://stackoverflow.com/questions/949798/foreach-can-throw-an-invalidcastexception-damn@silky: if you use VS, you can point your mouse to var and you'll see a tooltip with the actual item type
Yacoder
+7  A: 

var is mostly useful for anonymous types (you cannot create one without it). I have also seen others use it to reduce typing and redundant type information through type inference.

I personally find that it can hurt readability when it is used to reduce typing - remember that you spend 1% of your time writing the code and 99% of the time reading it.

// the compiler may be able to infer the type
// of "foo" but I certainly cannot without 
// viewing the implementation of "doSomething".
var foo = doSomething();

Edit: The main thing to remember (and this is common to all matters of coding style) is that you need to choose a style and use it consistently. As long as you like it and have a reason for using it that you feel is sound then you have won the battle :)

Andrew Hare
Not sure I agree with the bit about readability.
Ty
Agree but only when used with methods like your example, but not when creating new objects OR using commonly known methods like some of the new extensions Where(), Any(), First() etc...
Darko Z
Having meaningful method names and just inspecting the surrounding code would give some idea but at the end of the day I guess it comes down to personal preference.
Ty
var foo = doSomething();dim foo = doSomething(); 'Swear I've seen this somewhere...Before you tear my head off I do understand that these do mean different things, but VB.Net is rubbing off on C#, albeit slowly
Spence
+100 for the 1%/99% comment. This problem is especially evil when using `var` with methods that return numeric types. You can easily end up doing `int` math when you think you're doing `float` math.
MusiGenesis
@Spence: you hit the nail right between the eyes with your comment. I went the VB(3-6)-to-C# route, and it makes me cry to see this stuff coming back (and being hailed as "progress"). Don't get me started on `dynamic`.
MusiGenesis
@MusiGenesis: `var != variant`, `dynamic != variant`! Each of these (`var` and `dynamic`) have their uses. They can be abused, but so can any programming construct. Some are particularly prone to abuse (`goto`) but the benefits that `var` and `dynamic` provide in certain situations far outweigh the negatives that arise from abuse, laziness and misapplication.
Jason
Dynamic is a huge step forward for both com interop and DLR interop. However I think it has massive potential for abuse if used incorrectly. Anyone who has tried to port office code from vb.net to C# will know what I'm talking about. Linking a hotkey to type ref missing for you 27 times for EVERY freaking call is the kind of thing you never want to do again.
Spence
@Jason: (`var` == `variant`) != my point. Obviously there are differences between the constructs, but one of the more common uses of `var` leads to the same class of errors that `variant` produced. And even `variant` provided benefits in certain situations.
MusiGenesis
+3  A: 

How about anonymous classes?

var mySomething = new { Name = "Hello", Age=12 };
mezoid
yup, but what design/construct would require this?
moogs
+1  A: 

My favorite non-LINQ usage is in conjunction with foreach. Specifying the type explicitly instructs the compiler to do a cast if necessary, while simply using var is a simple way to ensure I really have the item type I think I have.

Abraham Pinzur
example? If I have a collection of objects, why would I want do interact with them by some other way rather than a common interface?
moogs
+1  A: 

I find it invaluable in prototyping, it lets me quickly store results from functions / properties and also enables me to adjust the return types from those functions with less cleanup afterwards. It's a (wee) bit like an interface for the methods, it lets me worry less about the concrete return types and more about the intent of the method.

As others have mentioned it's also nice to use when initializing new instances of objects; having Foo foo = new Foo(); is redundant. var foo = new Foo(); is just as readable, even better if there's multiple declarations...

var connString = BuildConnectionString();
var sqlConn = new SqlConnection(connString);
var commandText = BuildCommandText();
var sqlComm = new SqlCommand(commandText, sqlConn);

vs.

string connString = BuildConnectionString();
SqlConnection sqlConn = new SqlConnection(connString);
string commandText = BuildCommandText();
SqlCommand sqlComm = new SqlCommand(commandText, sqlConn);
STW
+1  A: 

When using MVC and having a client controller to return all your ajax requests, you will pretty much always use a var, because with an anonymous type you can only send the data needed by the application back to the client.

var response = new { var1 = "bla", var2 = "foo" };
return JSon(response);
Jan Jongboom
Nope, this is just being lazy not declaring var1 and var2 as strings, right?
moogs
No this is creating a json object with var1 and var2 as properties. Nothing to do with lazy. I might create this object from a business entity that contains way too much info for my client f.e.
Jan Jongboom
yup, but as with the other answers, this is just syntactic sugar. you can implement this w/o the var keyword, right?
moogs
Only if you want to create an object class for everything you'll send back to the client, which doesn't makes sense, because you're outputting it as JSON which doesn't care wether you have a real class or not.
Jan Jongboom
i'm not misunderstanding you :) you just described a syntactic sugar.
moogs
A: 

I've read somewhere that it's recommended that you use "var" in cases where you're calling code in a module not written by you, and that returns an object who's type is subject to future changes. If you were to write a wrapper to that external module, and you would only forward the result, than using var to temporarily store it would make your code still valid if/when the data type returned by the external call changes. Also, if you know that this result is some kind of collection, but again, not of a particularly stable kind, assigning to var and then iterating could still work in the event of further change.

luvieere
That won't work. `var` is just syntactic sugar. It doesn't make the type anonymous. As soon as you need to perform operations with the variable you're going to have to work within a specific type. Even if you're just writing a wrapper, you'd have to define the return type for your wrapper method since `var` can't be used in method signatures. It can make quick changes a little easier because if you change a data type you have one-less place to change it, but that's about it.
Dan Herbert
+1  A: 

I use var for nearly every assignment to a local variable. This really limits the amount of code changes I have to make if a particular method's return type changes. For example, if I have the following method:

List<T> GetList()
{
    return myList;
}

I could have lines of code all over the place doing local variable assignment that looks like this:

List<T> list = GetList(); 

If I change GetList() to return an IList<T> instead, then I have to change all those lines of assignment. N lines of assignment equals N+1 code changes if I change the return type.

IList<T> GetList()
{
    return myList;
}

If, instead, I had coded like the following:

var list = GetList(); 

Then I only have to change GetList() and the rest will be verified through compilation. We're off and running with only one code change. Granted, the compiler will complain if there was code depending on list to be a List<T> and not an IList<T>; but those should be fewer than N.

Travis Heseman