You're confusing classes and instances. I would recommend you completely avoid nesting one class inside another class; it's an active hindrance to your learning and you will probably never in your coding life need to use a nested class
Change your code thus:
//in file Order.cs
public class Order{
public string OrderID {get; set;}
public Address ShipTo {get; set;}
public Address BillTo {get; set;}
}
//in file Address.cs
public class Address {
public string Address1 {get;set;}
public string Address2 {get;set;}
}
Here I'm drawing a clear distinction between what something is (a class, like Address) and what it means (the name of the property, like the address you ShipTo versus the address you BillTo)
ShipTo and BillTo are both Addresses, and they may be same place or different, but they have different purposes. The name of the property reflects the purpose of the data, whereas the name of the class represents the structure of the data/what real world object or notion is modelled
Now you set them up like:
Order o = new Order();
o.OrderId = 1234;
o.ShipTo = new Address();
o.ShipTo.Address1 = "One Microsoft Way";
o.ShipTo.Address2 = "Redmond";
//this uses an initializer to set properties; same thing
o.BillTo = new Address () {
Address1 = "One Infinite Loop",
Address2 = "Cupertino"
}
You can use code like the first way to access your properties later:
public void SomeMethod(Order x){
x.BillTo.Address2 = "Cuppateanow";
Console.WriteLine(o.BillTo.Address1);
}
(Initializers help neaten up creating objects but there isn't a syntax like it for accessing data later, only for creating)
Remember, just because you make an Order with:
Order o = new Order();
Doesn't mean that o.BillTo
is set to anything. C# does not create everything hierarchically for you. If you create an order but do not create a BillTo address and you then try to access the BillTo address you will get a NullReferenceException. You must make sure you have done a o.BillTo = new Address()
before you try to o.BillTo.Address1 = ""
Side note; agree with Amy's point. Avoid ever pluralizing the name of a class. If a class is a collection of things you should end its name with "Collection" unless its name makes it obvious that it is a collection (like List, Hashset)
Properties that are a single entity should have a singular name
public string OrderId ...
Properties that are a collection should have a plural name
public List<Address> Addresses ...
In this latter case your class might have an enum telling what type of address it is, and then an order can have any number of any types of address and this be very flexible- perhaps you will write logic that only allows one shipping and billing but you will send order updates out to every correspondence address associated with the order:
enum AddressType{
Shipping,
Billing,
Correspondence
}
class Address{
...
public AddressType AddressType ...
}
(Or we could subclass address.. but I'll leave that discussion for another tine)