Redundancy in C#?

前端 未结 17 1542
猫巷女王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 20:02

    instead of thinking of it as redundant, think of that construct as a feature to allow you to save a line.

    instead of having

    List distances; distances = new List();

    c# lets you put them on one line.

    One line says "I will be using a variable called distances, and it will be of type List." Another line says "Allocate a new List and call the parameterless constructor".

    Is that too redundant? Perhaps. doing it this way gives you some things, though

    1. Separates out the variable declaration from object allocation. Allowing:

    IEnumerable distances = new List();
    // or more likely...
    IEnumerable distances = GetList();
    

    2. It allows for more strong static type checking by the compiler - giving compiler errors when your declarations don't match the assignments, rather than runtime errors.

    Are both of these required for writing software? No. There are plenty of languages that don't do this, and/or differ on many other points.

    "Doctor! it hurts when I do this!" - "Don't do that anymore"

    If you find that you don't need or want the things that c# gives you, try other languages. Even if you don't use them, knowing other ones can give you a huge boost in how you approach problems. If you do use one, great!

    Either way, you may find enough perspective to allow yourself to say "I don't need the strict static type checking enforced by the c# compiler. I'll use python", rather than flaming c# as too redundant.

提交回复
热议问题