I’m working on learning C# and I’ve ran into a problem with an example in my book.
I cant figure out why it sets my Room objets Exit to the appropriate Loactions, but my RoomWithDoor.Exits to null.
public Form1()
{
InitializeComponent();
CreateObjects();
MoveToANewLocation(livingRoom);
}
public void CreateObjects()
{
livingRoom = new RoomWithDoor("living room", "an antique carpet", "an oak door with a brass knob");
livingRoom.Exits = new Locations[] { diningRoom, kitchen };
livingRoom.DoorLocation = frontYard;
diningRoom = new Room("dining room", "crystal chandelier");
diningRoom.Exits = new Locations[] { livingRoom, kitchen };
abstract class Locations
{
public Locations(string name)
{
this.name = name;
}
public Locations[] Exits;
private string name;
public string Name { get { return name; } }
class Room : Locations
{
public Room(string name, string decoration)
: base(name)
{
this.decoration = decoration;
}
class RoomWithDoor : Room, IHasExteriorDoor
{
public RoomWithDoor(string name, string decoration, string doorDescription)
: base(name, decoration)
{
this.doorDescription = doorDescription;
}
So, this works
private void MoveToANewLocation(Locations newLocation)
{
currentLocation = newLocation;
currentLocationExit = currentLocation.Exits[0];
MessageBox.Show(diningRoom.Name);
but this dose not
MessageBox.Show(livingRoom.Exits[0].Name);
This doesn’t work as you expect. Since you assign a new value to
diningRoomafter you assignlivingRoom.Exits,livingRoom.Exitswill still have the valuediningRoomhad at the time of assignment, which is likelynull.