Redundancy in C#?

前端 未结 17 1610
猫巷女王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:41

    What's redudant about this?

    List listOfInts = new List():
    

    Translated to English: (EDIT, cleaned up a little for clarification)

    • Create a pointer of type List and name it listofInts.
    • listOfInts is now created but its just a reference pointer pointing to nowhere (null)
    • Now, create an object of type List on the heap, and return the pointer to listOfInts.
    • Now listOfInts points to a List on the heap.

    Not really verbose when you think about what it does.

    Of course there is an alternative:

    var listOfInts = new List();
    

    Here we are using C#'s type inference, because you are assigning to it immediately, C# can figure out what type you want to create by the object just created in the heap.

    To fully understand how the CLR handles types, I recommend reading CLR Via C#.

提交回复
热议问题