0

I come up with a problem in creating a program in C#. My problem is a NullReferenceException. I use arrays of lists. I will present below the part of code where I deal with the exceptions:

List<int>[] selected_universities = new List<int> [num_candidates];
int university_code;
for (i = 0; i < num_candidates; i++)
{
    Console.WriteLine("Please give the increasing code from 1 to " + num_universities + " in descedant sorted sequence of the universities you would like to enter.");
    Console.WriteLine("Press 0 to terminate your list");
    for (i = 0; i < num_universities; i++)
    {
        try
        {
            Console.WriteLine("Give your code now...");
            university_code = Convert.ToInt32(Console.ReadLine());
            if (university_code == 0) break;
            else selected_universities[i].Add(university_code);
        }
        catch (NullReferenceException e)
        {
            Console.WriteLine("The exception: " + e + " has occured!");
        }
    }
}
List<int>[] temporarily_success_candidates = new List<int>[num_universities];
for (i = 0; i < num_universities; i++)
{
    temporarily_success_candidates[i].Add(0);
}
Rob Purcell
  • 1,285
  • 1
  • 9
  • 19
Jimbo_ai
  • 167
  • 1
  • 13
  • Please format code correctly (indent with 4 spaces in the editor) – milo526 May 10 '15 at 18:53
  • you haven't shown which object is throwing the null reference exception, but it's hard to imagine your case isn't covered in the well known article on the subject. http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it?/ – Claies May 10 '15 at 18:56

1 Answers1

0

The problem is here

selected_universities[i].Add(university_code);

You try to add an item in a list that hasn't be initialized at all. It is null.

This List<int>[] selected_universities = new List<int> [num_candidates]; will create an array in which you will store list of integers. However, if we say that the array has 10 items, all of the 10 items would be null. In order you solve this you could try the following:

List<int>[] selected_universities = 
{
    new List<int> {},
    new List<int> {},
    new List<int> {},
    new List<int> {},
    new List<int> {}
};

The above declaration creates an array of five empty lists of integers. Now you could access any of the lists in the array using it's index and then add as many integers as you want.

Christos
  • 53,228
  • 8
  • 76
  • 108