I’m a C# beginner and am struggling a little bit with how classes relate to one another.
I am trying to code up a very simple elevator simulation. I have a class for Elevator:
class Elevator
{
public int currentFloor;
public Elevator()
{
currentFloor = 0;
}
public void ascend()
{
currentFloor++;
}
public void descend()
{
currentFloor--;
}
}
Very simple. This works, I can instantiate a new elevator object and have it go up and down, etc…
Now, I want to create a building object, so I created a new class for Buildings. However, I am now stuck – how do I add variable amounts of elevator objects to my buildings? For example, I might want to instantiate a building with 3 elevators, or another with 5…
I started creating a solutiomn where the building class has a List of elevators I can dynamically add to, but that seems so obtuse. So what I am looking for is something like:
Building office = new Building();
office.elevator1 = new Elevator();
office.elevator2 = new Elevator();
which obviously doesn’t work because I don’t have elevator1 and elevator2 declared in the Building class. What is the best/cleanest way to accomplish what I am looking to do? Also, what is this called? I Googled a ton of terms – class belongs to another class, instantiating a class from another class, similar terms with object instead of class… I’ve also looked over some of the elevator simulator code out there, but couldn’t find anything dynamic like I’m looking for…
Having a
List<Elevator>is quite appropriate here; it describes the real-world model very well.Perhaps it would be better if it were an
Elevator[](in the sense that perhaps it should not be possible to change the number of installed elevators after the building has been erected), but that’s not absolute.In any case, the collection of elevators should be exposed as a read-only property of appropriate type because it doesn’t make sense to swap it with another one.