What is the point of the var keyword?

The var keyword eliminates the need for an explicit type declaration, and I read with interest the SO discussion when this may be appropriate.

I also read (but not used) Boo , which seems to take a step forward, making it optional for declaring a local variable . With Boo, both type and declaration are implied.

What makes me wonder why C # designers didn't include the var keyword at all?

Update : Yes, var supports anonymous types, but anonymous types themselves do not require the var keyword ...

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

against

 anon = new { Name = "Terry", Age = 34 }; 
+41
variables c # boo
Oct. 16 '08 at 15:59
source share
8 answers

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

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

As other commentators note, LINQ uses this for its anonymous types. However, LINQ is actually an instance of a more general problem when the type of the right side of the expression is either unknown to the programmer or is extremely detailed. Consider:

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

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

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

By reducing duplication of information, errors are eliminated. Note that errors are not just printed here: it is possible that the type of the left expression will be masked in such a way that the compiler can safely drop from left to right, but the actuation actually loses some Rvalue property. This is even more important when the types returned by r may be unknown or anonymous.

+42
Oct 16 '08 at 16:12
source share

Without the var keyword, it becomes possible to accidentally create a new variable if you actually intended to use an existing variable. eg.

 name = "fred"; ... Name = "barney"; // whoops! we meant to reuse name 
+44
Oct. 16 '08 at 16:04
source share

I understand the need for var, and it works great for her. The lack of a keyword and just the definition of variables on the fly without type is scary. Your harm to the next guy who should support your code or yourself if you need to remake a code that you haven’t touched for more than a year. I'm not sure if this is the door that should open in C #, and I hope this is not the case, since var already causes readability problems when used when it is not needed.

Almost every .net 3.5 example I see recently has all the variables defined with var.

The assertion I am making is that it really sacrifices readability in order to preserve keystrokes when it is 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 use 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 argument will be, just name the function better ...

 var weight = GetExactWeightOfTheBrownYakInKilograms(); 

I still don’t know what will return. This is int, decimal, float, weight object, what? I still need to spend time looking for this ... I need an intellisense wallet to save the day from lazy programming. May include return type in function name. Good idea, now using var didn’t save us anything, forcing all my functions to have real long names.

I think people just use var, and this leads to lazy programming, which in turn leads to more complicated code reading. Each time you enter the var keyword, you should have a good reason why you are using it, and not explicit.

+34
Apr 29 '09 at 22:27
source share

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

Obviously where the variable is declared:

 var myVariable = SomeCodeToSetVariableHere; myVariable = SomeOtherCodeTOSetVariable; 

It is not clear where the variable is declared:

 myVariable = SomeCodeToSetVariableHere; myVariable = SomeOtherCodeTOSetVariable; 

These are too simplistic examples. I think you can see where this is happening. In difficult situations, it would be nice to find a place where the variable is actually defined.

+5
Oct. 16 '08 at 16:06
source share

In your question, var adds a value to the code, telling the compiler that the word anon now legal for use anywhere you expect to see an element of the type implied in the task. The requirement of introducing names into the compiler like this allows the compiler to reject something that it is not explicitly allowed to do, and thus catch some kinds of errors at compile time so that they do not explode at run time.

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

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

The problem with resolving this method is that it turns something into the left side of any assignment where the name was not previously in the variable declaration, even if it is really a typo. If later in the program you assign something else to the anon, and then refer even more to the new value, but the middle operator has a typo, you have a problem that will not be displayed until runtime.

Your answer: Boo does this, so it should be okay, or at least possible. But this is a red herring. We are talking about C #, not Boo. One of the goals of C # is to have a language in which the compiler can catch as many errors as possible. Boo also wants to do this, but he also wants to be more like Python. Therefore, he sacrifices some (not all) C # security for compilation in exchange for syntax like python.

+4
Oct 16 '08 at 16:54
source share

Disclaimer: my examples are Java, because this is what I know, but the concepts must be identical.

I voted for the answer, which I consider critical (it is too easy to accidentally create a new variable).

 bill=5; bi11=bill+5 

What is the value of the account?

However, I find it sometimes annoying to type:

 DataOutputStream ds=new DataOutputStream(); 

It seems redundant, but to be honest, there is nothing wrong with that. You no longer need to enter it twice, and it is very useful. It takes time when you have questions - when you don’t know how to use any API. If it’s really hard for you to type this type of ad twice, then why are you wasting your time here? Since you started reading this, you could enter 30 or 40 ads, enough for every ad that you need in the next two weeks.

I think I say that, although I understand that emotional stress, which can be repeated by itself, can cause consistency, clarity and the ability to make more intelligent tools, makes it WELL worth it.

One more thing: BRIDGE of the time when the code should not be similar to my example above. What you should do is:

 DataOutput ds=new DataOutputStream(); 

This immediately hides the fact that you are using a particular class in the template. This template should be able to perform all the operations necessary for your class. Later, if you want to replace ds with some other kind of stream, just changing this single line will fix it. If you used functions that are not available for DataOutput, other than DataOutputStream, the editor will easily know about it and inform you.

+1
Oct 16 '08 at 16:26
source share

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

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

Anonymous types can be used in places other than Linq.

var is extremely useful for Linq. In fact, according to one expert author, " Without" var ", LINQ is becoming too painful to use. "

0
Oct. 16 '08 at 16:01
source share

For anonymous types that, among other things, support LINQ.

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

-one
Oct. 16 '08 at 16:01
source share



All Articles