Вопрос

I am currently teaching a colleague .Net and he asked me a question that stumped me.

Why do we have to declare?

if var is implicit typing, why do we have to even declare?

Animal animal = new Animal();

becomes

var animal = new Animal();

could become

animal = new Animal();

The implicit typing would still mean that this is a statically typed variable.

If two different types are assigned to the variable, if they do not share a base class, (other than object), that could be a compiler error.

Is there a technical reason this could not be done or is it stylistically we like havein

Это было полезно?

Решение

Of course, that would be possible.

I can think of a few reasons you don't want this:

  1. What is the scope of your variable? Not clear if you don't tell the compiler. Will animals in two methods become a private variable or two method scoped variables?
  2. What if the name is a typo? You will never know.
  3. What if you already assigned a value to this variable and then try to assign a new value which is incompatible with the last (i.e javascript style) (credits to Mario Stoilov)

Другие советы

One very important reason is that it helps to prevent errors caused by accidentally mistyping a variable name.

Imagine, you want to reassign string myString to have a new value:

myString = "New value";

But you accidentally type this:

myStrimg = "New value";

This will cause a compile-time error. However, if you allow implicitly created variables per your question, this will silently create a new variable, with predictably hilarious results...

As suggested by Brad Smith http://www.brad-smith.info/blog/archives/336 :-

There seems to be a tendency for some programmers to use var for every variable declaration. Sure, the language doesn’t stop you from doing this and, indeed, MSDN admits that this is a “syntactic convenience”… But it also warns quite strongly that:

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.

Implicitly Typed Local Variables (C# Programming Guide), MSDN

I discovered recently that the commonly-used tool ReSharper practically mandates liberal use of var. Frankly, this isn’t helping the situation. There are some developers who try to argue the stance that var somehow improves readability and broader coding practices, such as this article:

By using var, you are forcing yourself to think more about how you name methods and variables, instead of relying on the type system to improve readability, something that is more an implementation detail…

var improves readability, Hadi Hariri

I agree with the premise of the quote above, but not with the end result. On the contrary, the overuse and misuse of var can lead to some very bad habits…

Let’s look at the argument against the widespread use of var (and for its sparing, correct use):

Implicitly-typed variables lose descriptiveness

The type name provides an extra layer of description in a local variable declaration:

 // let's say we have a static method called
 GetContacts() // that returns System.Data.DataTable  
 var individuals = GetContacts(ContactTypes.Individuals); 

 // how is it clear to the reader that I can do this?   
 return individuals.Compute("MAX(Age)", String.Empty);

My variable name above is perfectly descriptive; it differentiates between any other variables populated using GetContacts() and indeed other variables of type DataTable. When I operate on the variable, I know that it’s the individual contacts that i’m referring to, and that anything I derive from them will be of that context. However, without specifying the type name in the declaration, I lose the descriptiveness it provides…

   // a more descriptive declaration   
   DataTable individuals = GetContacts(ContactTypes.Individuals) 

When I come to revisit this body of code, i’ll know not only what the variable represents conceptually, but also its representation in terms of structure and usage; something lacking from the previous example.

Extra Notes :-

Here are a couple of good/bad examples based on a reasonable usage of implicit variable declaration…

  • Good:

     var numbers = new int[] {1, 2, 3, 4};
    
     var stringbuilder = new StringBuilder();
    
     var cars = new List();
    
     var orders = new Dictionary();
    

+/- OK with either (but prefer explicit declaration):

 int pages = 10;
 string username = “john”;
var username = “john”;
var order = GetOrder(orderId); // ok if the type is Order, otherwise not
 for (var x = 1; x < 10; x++)
  • Bad:

       var settings = GetInboxSettings(); // not obvious at all
    
      var userId = GetUserId(); // ambigous, is this guid, string, int or a custom UserId object?
    
       Dictionary orders = new Dictionary(); // redundant
    

When we declare a variable xxx, we indicate the following to our tooling

  • make room for an object
  • that will live in this scope
  • and be of this type (optionnally)

What we say to our humans is

  • an object named xxx exists in this scope
  • of this type (optionnally)

The scope is essential to both aspects, since the tooling needs to know how long the variable will live, and the humans need to see where a variable lives. The type can be a good information to have, but many languages live without it so I'd argue it is not as important, but YMMV

The compiler can determine what the scope of a variable would be, for example by deciding that the first encounter of a variable name is the declaration of the variable, and any word with the same name below that is a reference to that variable. Humans, on the other hand, cannot keep track of this kind of complexity successfully.

So I would say that we have one good reason to declare variables: to tell the humans reading our code that it exists. Declaring variables increase their visibility and clarifies information that is essential to our understanding of the program.

There must be many reasons. One of the reason I can think of is ambiguity between property/field reference versus new variable.

However, probably C# compiler team can still develop such a feature. But using var simplified everything. We saved design effort, development effort, testing effort and maintenance effort. Most important, it makes you code more readable.

Well I am not disputing the facts which are put across here in some answers. Rather I would like to answer differently:

int count;
if(someConditionIsTrue)
    count = 3;
else count = 1;

I can not use "var count" here. Can I? Now which one of the following two lines looks pretty :

Tuple<int, string, bool, float> tuple = new Tuple<int, string, bool, float>(1, "p", true, 3.0f);

OR

var tuple = new Tuple<int, string, bool, float>(1, "p", true, 3.0f); 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top