0

Here is a simplified version of my code:

   class House
{
    private string owner;
    private int[] roomArea = new int[10];

    public string Owner { get; set; }
    public int[] RoomArea { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        House[] london = new House[100];
        for (int i = 0; i < 100; i++)
        {
            london[i] = new House();
        }

        london[0].Owner = "Timmy";
        london[0].RoomArea[0] = 15; // Error points to this line

        Console.WriteLine("Room 1 in " + london[0].Owner + "s house has the area of " + london[0].RoomArea[0] + "square meters");


    }
}

I get the following error:

 Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

I've looked at this this question/solution, yet I can't pinpoint what's exactly wrong with my code.

user2757799
  • 105
  • 1
  • 1
  • 6
  • 3
    `RoomArea` is not initialized. The `RoomArea` property is not using the `roomArea` private member, it is creating it's own member behind the scenes to store the values, however, you're not initializing it before trying to use it. – RJM Oct 17 '17 at 02:17

1 Answers1

2

You need to initialize RoomArea. Even though you initialize inside the class it is creating it's own member , but in order to add values you need to initialize it

london[0].RoomArea  = new int[10];
london[0].RoomArea[0] = 15; 
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396