What's the point of the var keyword? [duplicate]
Asked Answered
Y

9

50

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 };
Yung answered 16/10, 2008 at 15:59 Comment(4)
I'm not touching this with a 10-meter pole. Well, other than to say I agree with you. I don't get it either. :)Urita
eh, how is your second line example valid code in c#?Zlatoust
@Pauli Østerø - it's not, the question (long since answered) is why not?Yung
Boo seems to be dead. What exactly did you read there? Maybe this should better be explained instead of being guessed from a dead URL.Langley
H
46

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.

Hatpin answered 16/10, 2008 at 16:12 Comment(1)
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).Goldy
B
48

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
Beverleebeverley answered 16/10, 2008 at 16:4 Comment(2)
Having var also stops you accidentally reusing a variable, as var name = "fred"; .... var name = "barney"; can be spotted by the compiler.Travancore
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.Cobaltic
H
46

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.

Hatpin answered 16/10, 2008 at 16:12 Comment(1)
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).Goldy
D
42

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.

Dab answered 29/4, 2009 at 22:27 Comment(4)
everytime you type out types on both side of the equal-sign, you are just wasting keystrokes by not using var.Zlatoust
@Pauli That's not what s/he is advocating.Kylander
The example is sucked out of thin air. Who cares about the units of measure as long as it's the same within an application. Oh you think it might be different? Please encode it explicitly using a wrapper.Hemotherapy
This clarifies things for me. I wanted to make sure there wasn't something I was missing as to why it was used. What I take from this and other answers is: use it rarely, and if you do, make sure it is clear.Hydro
I
6

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.

Impressible answered 16/10, 2008 at 16:6 Comment(0)
T
5

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.

Thorny answered 16/10, 2008 at 16:54 Comment(1)
Without some example It took me time to unroll the typo issue you're mentioning but yes that now definitely make sense to declare all variables prior to use them (explicitly typed or using var) ... I had the same question as @EdGuiness in mind for a few days looking for counterexamples and I feel released now :).Goolsby
D
3

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.

Demosthenes answered 16/10, 2008 at 16:0 Comment(1)
Thanks for the example with bill and bil1 ... yes that's the key point for why to declare things prior to use them.Goolsby
E
0

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."

Esperanzaespial answered 16/10, 2008 at 16:1 Comment(0)
K
0

Sometimes the type is pretty big. Imagine the type where you have a dictionary with generic type inside a dictionary. var will make this much more readable. Its also a coding practise.

Also, in case you want to create anonymous types like var randomData = { Id = 1, name = "Amit" }

I personally use types because sometimes you need to know what the function returns(In case, you want to pass the result to some other function.). Its easier to see the type than to hover the cursor on var. For eg: var result = GetSomethign();

Also, sometimes you need to navigate to the type pressing F12. This is not possible with var. This is a little irritating when you are in debugging mode because you cannot see the type while debugging. You need to stop debugging, see the type and start debugging again.

Killing answered 19/11, 2020 at 13:38 Comment(0)
B
-1

For anonymous types, which amongst other things support LINQ.

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

Botzow answered 16/10, 2008 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.