Take the following snippet:
List<int> distances = new List<int>();
Was the redundancy intended by the language designers? If so, why?
Take the following snippet:
List<int> distances = new List<int>();
Was the redundancy intended by the language designers? If so, why?
Because we're addicted to compilers and compiler errors.
Could also do:
Because declaring a type doesn't necessarily have anything to do with initializing it.
I can declare
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.
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:
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.
You could always say: