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.

1
  • 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. Commented Oct 17, 2017 at 2:17

1 Answer 1

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; 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.