Take the following snippet:
List distances = new List();
Was the redundancy intended by the language designers? If so, wh
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:
Person[] coworkers = new Employee[20];
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).
Could also do:
var distances = new List<int>();
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
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:
var distances = new List<int>();
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.
It's only "redundant" if you are comparing it to dynamically typed languages. It's useful for polymorphism and finding bugs at compile time. Also, it makes code auto-complete/intellisense easier for your IDE (if you use one).
Because declaring a type doesn't necessarily have anything to do with initializing it.
I can declare
List<int> foo;
and leave it to be initialized later. Where's the redundancy then? Maybe it receives the value from another function like BuildList().
As others have mentioned the new var keyword lets you get around that, but you have to initialize the variable at declaration so that the compiler can tell what type it is.