1

I'm new to C#, so this question might be an easy one. However I did not find any solution yet.

Description of the problem:

I want to create and empty array [4] of lists [length not know]. Later on I will read out four different channels and fill the list with objects created beforehand.

What I did so far

class objChannel 
{
    private int channel;
    public objChannel(int inputChannel)
    {
        channel = inputChannel;
    }

    public int Channel {get {return channel;}}
}

List<objChannel>[] listChannel = new List<objChannel>[4];

listChannel[1].Add(objChannel(1));

This does not work because of an null error.

Right now I have a work around like this:

List<objChannel>[] listChannel = {new List<objChannel> { new objChannel(1) },
                                  new List<objChannel> { new objChannel(2) },
                                  new List<objChannel> { new objChannel(3) },
                                  new List<objChannel> { new objChannel(4) }};

However, this will give me non-empty list.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
alias_paj
  • 148
  • 1
  • 9

2 Answers2

4

when you initialize your array of lists, you need to create empty lists as well like:

List<objChannel>[] listChannel = {new List<objChannel>(), new List<objChannel>(), new List<objChannel> (), new List<objChannel> ()};

or

for(int i = 0; i<4; i++)
{
    listChannel[i] = new List<objChannel>();
}
Jared Wilkin
  • 231
  • 3
  • 12
  • Is there an option to do that with even less code? I have to do a similar things which has 17 objChannels. I would like to avoid to write `new List()` so often. – alias_paj Jun 14 '16 at 17:49
  • yes, after creating the listChannel array, use a for loop to create new List objects, see updated answer – Jared Wilkin Jun 14 '16 at 18:00
  • Thanks. I thought there was some secret code I just don't know yet. Seems to be that I just have to do it the `for loop` or `while` way. – alias_paj Jun 14 '16 at 21:54
2

The reason your first code is failing is because you have to instantiate the listChannel[1] and then you can only call the instance method like:

listChannel[1] = new List<objChannel>();
listChannel[1].Add(new objChannel(1));

The other point to note is that the array index starts with 0 and not 1. (Although not sure if that use in the question was intentional).

Habib
  • 219,104
  • 29
  • 407
  • 436
  • Thanks @Habib for the fast reply. That works. Now I have the following `List[] listChannel = new List[4]; listChannel[0] = new List(); listChannel[1] = new List(); listChannel[2] = new List(); listChannel[3] = new List();` – alias_paj Jun 14 '16 at 17:18