-3

I want to initialize a list to a certain size

corridors = new List<Corridor>(new Corridor[rooms.Length - 1]);

As I've done here but I then want to add objects to the end of that list while leaving space between. so if outputted it would look like

[,,,,,,,,,,Corridor()] or

[Corridor(),Corridor(),Corridor(),Corridor(),,,,,,Corridor()]

I have tried this way already and its not working for me. I want to do it this way because the corridors that exist at the initialized size are all standard one and I'd like to be able to loop through those while being able to add special ones at the end.

What would be the best way about doing this?

  • So you want to leave `room.Length - 1` items free before adding new elements? So the first actually used index = `rooms.Length`? You can provide an index to `Insert` for that. – MakePeaceGreatAgain Mar 07 '19 at 16:22
  • 2
    You can't do that with a `List`, but you can do it with an array. If your list doesn't need to expand (i.e. you know the capacity beforehand), use an array. – itsme86 Mar 07 '19 at 16:23
  • `I'd like to be able to loop through those...` you will also want to bookmark [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/q/4660142/1070452) – Ňɏssa Pøngjǣrdenlarp Mar 07 '19 at 16:27

1 Answers1

2

If you initiate an array and then toList it you will get a bunch of null records that you can replace or add to the end of.

var corridors = new Corridor[10].ToList();
corridors.Add(new Corridor());
Ryan Schlueter
  • 2,223
  • 2
  • 13
  • 19