-3

I have this simple application to populate fields from a data model, The data model is called Order which has a nested class called Address. When I attempt to assign a value to Order.Address.city, I get the error message:

Object reference not set to an instance of an object.

I tried various different ways to correct the error, Order class doesn't seem to recognize the Address class.

Data Model is listed below....

namespace ConsoleApp1.DataModels
{
    public class Order { 
        public string name { get; set; }
        public string description { get; set; }
        public Address address { get; set; }

        
        public class Address 
        {
            public string city { get; set; }
            public string state { get; set; }
            public string zip { get; set; }
        }
    }
 }

C# code is below and error occurs when this line is executed:

myOrder.address.city = "Chicago";
using ConsoleApp1.DataModels;


namespace WalmartOrderProcessing
{
    class Program
    {
         static void Main(string[] args)
        {
            Order myOrder = new Order();

            myOrder.name = "John Doe";
            myOrder.description = "Contractor";

            myOrder.address.city = "Chicago";
            myOrder.address.state = "IL";
            myOrder.address.zip = "12345";
        }
    }
}
3
  • you have not initialized the Address property anywhere. That's why it's null. Commented Jun 8, 2024 at 14:54
  • this should work public Address address { get; set; } = new Address(); Commented Jun 8, 2024 at 14:56
  • A nested class nests the definition of the class within another class. When you instantiate an object of the parent class, the newly created object doesn't automatically instantiate a (or perhaps many) instance(s) of the nested class. You need to do that yourself (as everyone else has pointed out) Commented Jun 8, 2024 at 15:35

1 Answer 1

0

You aren't initializing the address member, so implicitly it's null. Initialize it and you should be fine:

public Address address { get; set; } = new Address();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.