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();
}
}
}