Take the following snippet:
List<int> distances = new List<int>();
Was the redundancy intended by the language designers? If so, why?
Take the following snippet:
List<int> distances = new List<int>();
Was the redundancy intended by the language designers? If so, why?
I see one other problem with the using of var for laziness like that
If you use var, the variable named "names" is typed as
List<string>,
but you would eventually only use one of the interfaces inherited byList<T>.
You can automatically use everything of that, but can you consider what interface you wanted to use at the time you wrote the code?
The var keyword does not improve readability in this example.
The reason the code appears to be redundant is because, to a novice programmer, it appears to be defining the same thing twice. But this is not what the code is doing. It is defining two separate things that just happen to be of the same type. It is defining the following:
List<int>
.List<int>
.Consider the following:
Here the non-redundancy is clearer, because the variable and the allocated object are of two different types (a situation that is legal if the object’s type derives from or implements the variable’s type).
The compiler improvements for C# 3.0 (which corresponds with .Net 3.5) eliminate some of this sort of thing. So your code can now be written as:
The updated compiler is much better at figuring out types based on additional information in the statement. That means that there are fewer instances where you need to specify a type either for an assignment, or as part of a Generic.
That being said, there are still some areas which could be improved. Some of that is API and some is simply due to the restrictions of strong typing.
The redunancy wasn't intended, per se, but was a side-effect of the fact that all variables and fields needed to have a type declaration. When you take into account that all object instantiations also mention the type's name in a new expression, you get redundant looking statements.
Now with type-inferencing using the var keyword, that redundancy can be eliminated. The compiler is smart enough to figure it out. The next C++ also has an auto keyword that does the same thing.
The main reason they introduced var, though, was for anonymous types, which have no name:
C# is definitely getting less verbose after the addition of functional support.
As others have said:
var
removes the redundancy, but it has potential negative maintenance consequences. I'd say it also has potential positive maintenance consequences.Fortunately Eric Lippert writes about it a lot more eloquently than I do: http://csharpindepth.com/ViewNote.aspx?NoteID=63 http://csharpindepth.com/ViewNote.aspx?NoteID=61