Redundancy in C#?

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

    The redunancy wasn't intended, per se, but was a side-effect of the fact that all variables and fields needed to have a type declaration. When you take into account that all object instantiations also mention the type's name in a new expression, you get redundant looking statements.

    Now with type-inferencing using the var keyword, that redundancy can be eliminated. The compiler is smart enough to figure it out. The next C++ also has an auto keyword that does the same thing.

    The main reason they introduced var, though, was for anonymous types, which have no name:

    var x = new {Foo = Bar, Number = 1};
    

提交回复
热议问题