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条回答
倾城 Initia
2楼-- · 2020-06-09 10:14

It's only "redundant" if you are comparing it to dynamically typed languages. It's useful for polymorphism and finding bugs at compile time. Also, it makes code auto-complete/intellisense easier for your IDE (if you use one).

查看更多
手持菜刀,她持情操
3楼-- · 2020-06-09 10:14

Your particular example is indeed a bit verbose but in most ways C# is rather lean.

I'd much prefer this (C#)

int i;

to this (VB.NET)

Dim i as Integer

Now, the particular example you chose is something about .NET in general which is a bit on the long side, but I don't think that's C#'s fault. Maybe the question should be rephrased "Why is .NET code so verbose?"

查看更多
男人必须洒脱
4楼-- · 2020-06-09 10:16

In many of the answers to this question, the authors are thinking like compilers or apologists. An important rule of good programming is Don't repeat yourself!

Avoiding this unnecessary repetition is an explicit design goal of Go, for example:

Stuttering (foo.Foo* myFoo = new(foo.Foo)) is reduced by simple type derivation using the := declare-and-initialize construct.

查看更多
够拽才男人
5楼-- · 2020-06-09 10:18

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

查看更多
Anthone
6楼-- · 2020-06-09 10:19

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

distances = []
查看更多
\"骚年 ilove
7楼-- · 2020-06-09 10:20

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

查看更多
登录 后发表回答