Redundancy in C#?

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

    You could always say:

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

    A historical artifact of static typing / C syntax; compare the Ruby example:

    distances = []
    
    0 讨论(0)
  • 2021-02-13 19:41

    What's redudant about this?

    List<int> listOfInts = new List<int>():
    

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

    • Create a pointer of type List<int> 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<int> on the heap, and return the pointer to listOfInts.
    • Now listOfInts points to a List<int> on the heap.

    Not really verbose when you think about what it does.

    Of course there is an alternative:

    var listOfInts = new List<int>();
    

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

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

    Use var if it is obvious what the type is to the reader.

    //Use var here
    var names = new List<string>();
    
    //but not here
    List<string> names = GetNames();
    

    From microsofts C# programing guide

    The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code

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

    Because we're addicted to compilers and compiler errors.

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

    I see one other problem with the using of var for laziness like that

    var names = new List<string>();
    

    If you use var, the variable named "names" is typed as List<string>, but you would eventually only use one of the interfaces inherited by List<T>.

    IList<string> = new List<string>();
    ICollection<string> = new List<string>();
    IEnumerable<string> = new List<string>();
    

    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.

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