0

I'm trying to get a better understanding of classes, the class 'Address' is used as a type in the property 'ShippingAddress' in the class 'Person', but I was wondering how do I assign values to the address properties because the way it is below gives me an error:

Found on .NET Tutorials

**An unhandled exception of type 'System.NullReferenceException' occurred in Classes_and_Objects.exe

Additional information: Object reference not set to an instance of an object.**

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace Classes_and_Objects
    {
        class Program
        {
        static void Main(string[] args)
        {
            Person john = new Person();
            john.FirstName = "John";
            john.LastName = "Doe";
            john.ShippingAddress.StreetAddress = "78 Fake Street" ;
            john.ShippingAddress.City = "Queens";
            john.ShippingAddress.State = "NY";
            john.ShippingAddress.PostalCode = "345643";
            john.ShippingAddress.Country = "United States";
            }

        }

        public class Address
        {
            public string StreetAddress { get; set; }
            public string City { get; set; }
            public string State { get; set; }
            public string PostalCode { get; set; }
            public string Country { get; set; }
        }
        public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public Address ShippingAddress { get; set; }
        }

    }
    }

2 Answers2

1

You need to instantiate the address too. Here is how you should write your code:

static void Main(string[] args)
{
    Person john = new Person();
    john.FirstName = "John";
    john.LastName = "Doe";
    john.ShippingAddress = new Address();
    john.ShippingAddress.StreetAddress = "78 Fake Street" ;
    john.ShippingAddress.City = "Queens";
    john.ShippingAddress.State = "NY";
    john.ShippingAddress.PostalCode = "345643";
    john.ShippingAddress.Country = "United States";
}
Sparrow
  • 2,278
  • 1
  • 24
  • 27
0
Jhon.shippingadress = new Address();
Maske
  • 614
  • 13
  • 29