Avatar of r_pat72
r_pat72
 asked on

Help on c# list

Hi,

I have a array of list & I am trying to add items to the array of list & getting object reference error. Could you see if anything wrong here.

         List<string>[] list = new List<string>[4];

   
        list[0].Add("test3");
        list[0].Add("test4");
 
        list[1].Add("test1");
        list[1].Add("test2");

      Messagebox.Show(list[0].ToArray());
     Messagebox.Show(list[1].ToArray());
C#WCF.NET Programming

Avatar of undefined
Last Comment
Bob Learned

8/22/2022 - Mon
Dmitry G

OK, you have created an array of lists but you haven't created lists in this array!
You have to create them explicitly.
ASKER CERTIFIED SOLUTION
Dmitry G

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
r_pat72

ASKER
Do I have to do something like this


List<string>[] list = new List<string>[4];

       list[0] =   new List<string>();
        list[0].Add("test3");
        list[0].Add("test4");
 
       list[1] =   new List<string>();
        list[1].Add("test1");
        list[1].Add("test2");

      Messagebox.Show(list[0].ToArray());
     Messagebox.Show(list[1].ToArray());
SOLUTION
Dmitry G

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Bob Learned

You should be able to use initializer syntax, like this:


            List<string>[] list = new List<string>[]
            {
                new List<string>{"test 1-1", "test 1-2", "test 1-3"},
                new List<string>{"test 2-1", "test 2-2", "test 2-3"}
            };

Open in new window

Your help has saved me hundreds of hours of internet surfing.
fblack61