tags:

views:

1382

answers:

8

The var keyword does away with the need for an explicit type declaration and I have read with interest the SO discussion of when it might be appropriate.

I have also read about (but not used) Boo which seems to take things a step further by making it optional to declare a local variable. With Boo, both the type and the declaration can be implied.

Which leads me to wonder, why did the C# language designers bother to include a var keyword at all?

Update: Yes, var supports Anonymous types, but anonymous types by themselves do not necessitate the var keyword...

var anon = new { Name = "Terry", Age = 34 };

versus

anon = new { Name = "Terry", Age = 34 };
A: 

I believe that var (and several other new keywords) were added specifically to support Linq.

var is the keyword used to create an anonymous type - see http://msdn.microsoft.com/en-us/library/bb397696.aspx

Anonymous types can be used in other places than Linq.

var is exceedingy useful for Linq. In fact, according to one expert author, "Without ‘var’, LINQ gets too painful to use."

DOK
A: 

For anonymous types, which amongst other things support LINQ.

http://www.blackwasp.co.uk/CSharpAnonTypes.aspx

BlackWasp
+26  A: 

Without the var keyword it becomes possible to accidentally create a new variable when you had actually intended to use an already existing variable. e.g.

name = "fred";
   ...
Name = "barney"; // whoops! we meant to reuse name
Ferruccio
Having var also stops you accidentally reusing a variable, as var name = "fred"; .... var name = "barney"; can be spotted by the compiler.
stevemegson
@stevemegson, good comment, I'll upvote if you make this an answer.
Ed Guiness
@stevemegson - good point. I hadn't though of that.
Ferruccio
This answer confuses two different questions: "why have var in a language that requires you to declare variables", and "why declare variables at all?" Accidentally creating a variable reuse is prevented by forcing you to declare them.
JSBangs
Great! Thanks for that. I've been wondering this for a while now and when I read this answer I felt REALLY stupid.
Stimul8d
+4  A: 

This is a bit subjective, but I think designing C# 3.0 to have the "var" keyword for implicitly typed variables instead of no keyword makes the code more readable. For example, the first code block below is more readable than the second:

Obvious where the variable is declared:

var myVariable = SomeCodeToSetVariableHere;
myVariable = SomeOtherCodeTOSetVariable;

Not obvious where the variable is declared:

myVariable = SomeCodeToSetVariableHere;
myVariable = SomeOtherCodeTOSetVariable;

These are over-simplistic examples. I think you can see where this goes. In complex situations it might be nice to be able to find the place where a variable is actually defined.

Jason Jackson
+15  A: 

Update: There are two related questions here, actually: 1. Why do I have to declare variables at all? 2. What use is "var" in a language that makes you declare variables?

The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below:

As other commenters have said, LINQ uses this for its anonymous types. However, LINQ is actually an instance of a more general problem where the type of the right-hand side of an expression is either unknown to the programmer, or is extremely verbose. Consider:

SomeGeneric<VeryLongTypename<NestedTypename>> thing = new   
SomeGeneric<VeryLongTypename<NestedTypename>>();

Verbose and error-prone, right? So now they let you do this:

var thing = new SomeGeneric<VeryLongTypename<NestedTypename>>();

By reducing the duplication of information, errors are eliminated. Note that there aren't just typing errors, here: it's possible for the type of the left-hand expression to be mistyped in such a way that the compiler can silently cast from left to right, but the cast actually loses some property of the rvalue. This is even more important when the types returned by the rvalue may be unknown or anonymous.

JSBangs
C# is not Boo. It doesn't support Duck Typing. The C# compiler determines the type of a var-declared variable based on the type of the object assigned to it - if the type is unknown, var cannot be used. Needed for anonymous types as the *programmer* can't specify the type (but the C# compiler can).
Shog9
A: 

disclaimer: my examples are Java because that's what I know, but the concepts should be identical.

I voted up the answer that I feel is critical (it's too easy to accidentally create a new variable).

bill=5;
bi11=bill+5

What's the value of bill?

That said, I find it somewhat irritating at times to type:

DataOutputStream ds=new DataOutputStream();

Seems redundant, but honestly there is nothing really wrong with it. It does not take you any longer to type it twice, and it's extremely helpful. What takes time is when you have questions--when you aren't sure just how to use some API. If it really bothers you to type that type declaration twice, then why are you wasting your time here? Since you started reading this you could have typed 30 or 40 declaration, enough for every declaration you'll need for the next two weeks.

I guess I'm saying that although I understand the emotional stress that repeating yourself can cause, the consistency, clarity and ability to make more intelligent tools makes it WELL worth while.

One more thing, MOST of the time the code should not be like my example above. What you should be doing is this:

DataOutput ds=new DataOutputStream();

This immediately hides the fact that you are using a concrete class into a template. That template should be able to do all the operations you need on your class. Later if you wanted to replace ds with some other kind of output stream, simply changing that single line will fix it. If you were using the features not available to DataOutput by casting to DataOutputStream, the editor will easily figure it out and let you know.

Bill K
+4  A: 

In your question, var adds value to the code by telling the compiler the word anon is now legal for use anywhere you'd expect to see an item of the type implied in the assignment. Requiring the introduction of names to the compiler like this allows the compiler to reject things it hasn't been explicitly told are allowed, and thereby catch certain kinds of errors at compile time so they don't blow up at runtime.

For example, in the update section of your question, you asked about this snippet:

anon = new { Name = "Terry", Age = 34 };

The problem with allowing it this way is that it turns anything on the left hand side of any assignment where the name didn't previously exist into a variable declaration, even if it's a really a typo. If later in the program you assign something else to anon and then even further on reference the new value, but the middle statement had a typo, you've got a problem that won't show up until runtime.

Your response is that Boo does it, so it must be okay or at least possible. But that's a red herring. We're talking about C#, not Boo. One of the purposes of C# is to have a language where the compiler can catch as many errors as possible. Boo wants to do that, too, but it also wants be more like Python. So it sacrifices some (not all) of C#'s compile-time safety in exchange for python-like syntax.

Joel Coehoorn
+10  A: 

I understand the need for var and it serves it purpose great. Having no keyword and just defining variables on the fly with no type is scary. Your hurting the next guy who has to maintain your code or yourself if you need to rework the code you haven't touched in over a year. I am not sure that is a door that should be opened in C# and I hope it isn't as var is already causing readability issues when being over used when it is not necessary.

Almost every .net 3.5 example I am seeing lately has all variables defined with var.

The arguement I make is that it really sacrifices readability for the sake of saving keystrokes when it is over used. For example:

// What myVar is, is obvious
SomeObject myVar = new SomeObject();

// What myVar is, is obvious here as well
var myVar = new SomeObject();

The problem I see is that people are using it everywhere... for example:

// WTF is var without really knowing what GetData() returns?
// Now the var shortcut is making me look somewhere else when this should
// just be readable!
var myVar = GetData();

// If the developer would have just done it explicitly it would actually
// be easily readable.
SomeObject myVar = GetData();

So the next arguement will be, just name the function better...

var weight = GetExactWeightOfTheBrownYakInKilograms();

Still don't know what is coming back. Is it an int, decimal, float, weight object, what? I still have to waste time looking it up... need the intellisense crutch to save the day from my lazy programming. Maybe include the return type in the function name. Good idea, now using var has saved us nothing except making all my functions have real long names.

I think people are just over using var and it is leading to lazy programming which in turn leads to harder to read code. Everytime you type out the keyword var, you should have a good reason why you are using it instead of being explicit.

Kelsey
I love the GetExactWeightOfTheBrownYakInKilograms().
Zifre