Redundancy in C#?

2020-06-09 10:01发布

Take the following snippet:

List<int> distances = new List<int>();

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

17条回答
爷、活的狠高调
2楼-- · 2020-06-09 10:21

Because we're addicted to compilers and compiler errors.

查看更多
小情绪 Triste *
3楼-- · 2020-06-09 10:22

Could also do:

var distances = new List<int>();
查看更多
我想做一个坏孩纸
4楼-- · 2020-06-09 10:25

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.

查看更多
Root(大扎)
5楼-- · 2020-06-09 10:26

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<int> distances = new List<int>();
// or more likely...
IEnumerable<int> 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.

查看更多
甜甜的少女心
6楼-- · 2020-06-09 10:29

You could always say:

 var distances = new List<int>();
查看更多
登录 后发表回答