0

I am writing a C# program that is supposed to write family information into a 2dimensional jagged array: Array[family][person]. In each field of the array I will have a class Person that contains 3 fields: name, surname and age. I am asking the user to input the size of the families and then the names and ages but when I input the surname the program crashes in the following line with the NullReferenceException:

JaggedArray[i][j].Name = Nachname;

I dont know what I did wrong, so any help is appreciated.

static void Main(string[] args)
{
    Console.WriteLine("Entry");
    Console.WriteLine();
    Console.Write("Number of families: ");
    int Families = Convert.ToInt32(Console.ReadLine());
    Person[][] JaggedArray = new Person[Families][];
    for (int i = 0; i < JaggedArray.Length; i++)
    {
        Console.Write("Number of familymembers for {0}. family:", i + 1);
        int Members = Convert.ToInt32(Console.ReadLine());
        JaggedArray[i] = new Person[Members];
        Console.Write("Surname: ");
        string Nachname = Console.ReadLine();

        for (int j = 0; j < Members; j++)
        {
            JaggedArray[i][j].Name = Nachname;
            Console.Write("{0}. Vorname: ", j + 1);
            JaggedArray[i][j].Vorname = "Peter";
            Console.Write("{0}. Alter: ", j + 1);
            JaggedArray[i][j].Alter = Console.Read();
        }
    }
}
Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157
  • 1
    Take a look at this question and answer: [What is a NullReferenceException and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it?rq=1). – Dirk May 24 '14 at 09:30
  • http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – Yuval Itzchakov May 24 '14 at 09:31
  • Indexes (of arrays) are 0-based. take i < JaggedArray.Length - 1. – Dieter B May 24 '14 at 09:32

0 Answers0