Redundancy in C#?

前端 未结 17 1547
猫巷女王i
猫巷女王i 2021-02-13 19:28

Take the following snippet:

List distances = new List();

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

相关标签:
17条回答
  • 2021-02-13 19:46

    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).

    0 讨论(0)
  • 2021-02-13 19:46

    Could also do:

    var distances = new List<int>();
    
    0 讨论(0)
  • 2021-02-13 19:48

    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

    0 讨论(0)
  • 2021-02-13 19:48

    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.

    0 讨论(0)
  • 2021-02-13 19:49

    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).

    0 讨论(0)
  • 2021-02-13 19:58

    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.

    0 讨论(0)
提交回复
热议问题