Note that there are some explanatory texts on larger screens.

plurals
  1. POC# - class instantiating other classes?
    primarykey
    data
    text
    <p>I'm a C# beginner and am struggling a little bit with how classes relate to one another.</p> <p>I am trying to code up a very simple elevator simulation. I have a class for Elevator:</p> <pre><code>class Elevator { public int currentFloor; public Elevator() { currentFloor = 0; } public void ascend() { currentFloor++; } public void descend() { currentFloor--; } } </code></pre> <p>Very simple. This works, I can instantiate a new elevator object and have it go up and down, etc...</p> <p>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...</p> <p>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:</p> <pre><code>Building office = new Building(); office.elevator1 = new Elevator(); office.elevator2 = new Elevator(); </code></pre> <p>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...</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload