views:

512

answers:

9

Possible Duplicate:
What’s the point of the var keyword?

Hello everyone,

I want to confirm whether my understanding is correct. If I do not use LINQ, then the only benefit of using var is to make brevity? Is that correct understanding?

thanks in advance, George

+16  A: 

No, you can use var to construct anonymous types, regardless of whether or not you're using LINQ:

var anon = new { Name = "Anonymous", Age = 42 };
LukeH
Can you then write to this anonymous type, so anon.Name = "New Name"; or is it fixed?
Callum Rogers
@C Rogers. Yes, it's a real type.
kenny
@C Rogers - Well, the properties of anonymous types are readonly.
JulianR
+3  A: 

It's also easier for working with types like this. When you have very long generic types, the type name can get in the way of visually identifying the variable name as part of a declaration.

Dictionary<string, Dictionary<int, ICollection<object>>>

especially if you go back through and change it to

Dictionary<string, IDictionary<int, ICollection<object>>>
280Z28
You can fix that with `using MyType = Dictionary<string, Dictionary<int, ICollection<object>>>;`
Daniel Earwicker
But not when it's the return type from a visible method. You'd have to keep the `using` statements consistent across all files that use it.
280Z28
A: 

I believe it is also used in the WCF (Windows communication Foundation) when dealing with data obtained via webservices and the like.

Garry
+1  A: 

If you're not using LINQ, var allows you to only declare the type of the variable once, instead of twice.

Example

var myObject = new MyObject();

vs

MyObject myObject = new MyObject();

This can only be done locally, and is also useful for declaring anonymous types.

Example

var myAnon = new { Name = "Something", Count = 45 };
Joseph
+1  A: 

Pretty much, yes. var may be used wherever the compiler can infer the type of the variable from whatever value you are assigning to it. (The type inference rules are quite complex however, so you may want to read the C# specification for a full understandin.)

It's not quite correct in that the var keyword is required for defining anonymous types. For example:

var foo = new { abc = 1, def = 2 };

which can be used outside of LINQ queries as well as inside, of course.

Noldorin
+2  A: 

From msdn:

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

MSDN Link Here

Sev
+2  A: 

Other than for LINQ queries I would be very cautious in using the var keyword. There are specific instance when you just need an anonymous type but this is few and far between I think. Var can lead to very confusing code as you have no idea what the type you are dealing with when reading the code unless you use the intellisense crutch.

It worries me more and more that I see so many snippets and bits of code that do the following... it's lazy and not what the var keyword was intended for:

// Not too bad but still shouldn't be done because the only gain you have is keystrokes
var Something = new SomeObject();

// Type here is not obvious, are you getting an int, double, custom object back???
var Something = GetLengthOfSpaghettiCode();

So use it for LINQ... use it for anonymous types (if you do use anonymous types outside of LINQ you should really scrutinize why you need to).

Quote from MSDN (very last line of article) regarding use of var:

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.

Don't use it as a short cut to save keystrokes, the next guy looking at your code will appreciate it.

Kelsey
Code completion and IDE suffice to aid developers looking at your code later (not a crutch, not lazy--just professional). Furthermore, good variable names expose the intent of your code. The var keyword is nice especially in the first example given in this response, since you would be engaging in Good thing: DRY (Don't Repeat Yourself). The second example is even better since the abstraction is further removed. As for the intended usage of var I would love to see a citation.
mkelley33
The second example is exactly why it is bad. Assume the function returned an int and then the code for the function was changed to return a double. You application could still compile just fine but but have totally un-intended results.
Kelsey
I think that's why unit testing and validation are good practices. If the intent is important enough as it relates to the type in question, then it should be unit tested and validated.
mkelley33
Or, more commonly, completely acceptable results. Usually the intent of the method and the meaning of its return type is obvious from its name.
Jacob
Word up Jacob. As for the citation about when to use var note that it doesn't explain the intent of the var keyword and its usage.
mkelley33
Kelsey, I just want to thank you for this comment. Developers who use "var" are in my mind, extremely lazy. Nothing irks me more when debugging code, than to have to question what the type of a variable is. Why should I have to read the entire line of code to see what this variable actually is? Because some chump couldn't be bothered to declare its type? Thanks again, glad to see someone here has common sense.
Kevin
The fallacy is in thinking that you need to know the type of every variable. Would it have been easier to read my last sentence if I put the grammatical type of each word in brackets before it? Or did you understand it just fine via context and definitions? Type is an implementation detail, and now we can treat it as such. The "saving keystrokes" strawman only obfuscates the issue, and is obviously not the goal of the keyword.
Bryan Watts
Bryan I am not disputing the goal of the keyword var. I think it is great for anonymous types and I think that was the reason it was introduced. I argue that var something = CreateSomething(); is a side effect of the feature. A side-effect that saves keystrokes at the cost of being less explicit.
Kelsey
@Kelsey You already have "something" twice in that statement. I don't see the value of adding it yet again just to tell the compiler something it already knows. Any human knows what it is: you named it "something", not "somethingElseEntirely". Plus, something I haven't seen mentioned, is that variable declarations become standardized. The eye learns to read them (like it does with for loops), and you don't have to read through a whole type name to know the kind of statement. You already have a label for the semantic meaning of the variable: its name. Do you really need to always know the type?
Bryan Watts
My example var something = CreateSometing(); was not to mean I was creating exactly that, it was suppose to be anything. Like my original var Something = GetLengthOfSpaghettiCode(); I don't know what var is until I go and look how it is being used. Same as var = 1; is it a int, unsigned int, nullable int, or a double even. Either way, the statement works and compiles so it comes down to coding style and preference. I don't like it. Doesn't mean I am right or wrong, it's my preference. This is not the forum to have this type of discussion ;)
Kelsey
Mistyped above (waiting for someone to jump all over it) var = 1; should be var something = 1;
Kelsey
A: 

I've also found that the use of var also eases refactoring in low-coupled designs. This is because we tend to strong type variables, but normally the code that follows is expecting weaker types. Using var you'll offset type changes to the compiler.

Hugo S Ferreira
A: 

I don't think using var should be a problem - and I prefer it for exactly the reasons of code readability. First of all, var is only syntactic sugar and just gets compiled away to a proper type when IL is emitted. And as far as the code readability goes, it makes more sense to focus on the purpose the variable is used for, and how it is assigned than just its type. VS .NET editor shows the type in the line following it anyway - if you just hover on it. So this shouldn't be a problem at all. And as far as the debugging goes - if you see Autos/Local/Watch windows - they display the types of all the members.

It makes more sense for me to see code like this:

var customers = GetCustomerList();
foreach (var customer in customers)
{
  customer.ProcessOrders();
}

as opposed to

List<CustomerObjectDeserializedFromWebService> customers = GetCustomers();
foreach (CustomerObjectDeserializedFromWebService customer in customers)
{
  customer.ProcessOrders();
}

var is in its fairness limited to using in local variable declarations which are also initialized at the time of declaration. And in that one case, if you omit the actual type it definitely improves readability IMO.

EDIT: And it would unfair on my part not to warn against the usages as below:

var x = 20;

This is not good; when the literal is applicable to multiple types, you need to know the default type of the literal and hence understand what is infered for the type of x. Yes, by all means, I would avoid such declarations.

Charles Prakash Dasari