Search code examples
c#.netgenericsprogramming-languages

Redundancy in C#?


Take the following snippet:

List<int> distances = new List<int>();

Was the redundancy intended by the language designers? If so, why?


Solution

  • 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:

    1. A variable named distances of type List<int>.
    2. An object on the heap of type 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).