Hello everyone,
I am a freshman in C#, and stuck with a logical/conceptual problem in my hobby project. I want a good object oriented approach, but can not figure out how :confused:
I've simplified my problem for easy understanding.
Consider, a class "Home", it has many different kind of Rooms. Each room share some common property and has many different properties.
Please read the code, its self explainatory.
Ques A : How to get all the rooms's appropriate data in "writeAllRoomData" function ?
Ques B : Is there a better way, so that each instance of Room(of a particular roomtype) does not have the burden of other roomtype's vars?
(e.g. in the first code below each instance of room will have struct vars of every roomtype)
Ques C : As in the actual code, type of rooms are too many. Is there a better way to make such code without checking for roomtype, everytime a function in room class want to edit properties of that particular roomtype, (e.g. by using interfaces or Polymorphic functions etc ?)
If yes, can you please provide a small sample code.
class home
{
OnButtonClick()
{
switch(something)
{
case A : roomType = enumRoomType.bedroom;
case B : roomType = enumRoomType.bathroom;
....
}
Room room = new Room(roomType);
listofRoom.Add(room);
}
writeAllRoomData()
{
foreach(room in listofRoom)
{
}
}
}
class Room
{
private enumRoomType roomType;
public void Room (enumRoomType roomType)
{
this.roomType = roomType;
}
struct BedroomVars{
public bool bed;
public int lamps;
}
BedroomVars _bedroomVars;
struct BathroomVars{
public bool tub;
public int soaps;
}
BathroomVars _bathroomVars;
struct kitchen{
...
}
...
public void SomeFunc();
{
switch(RoomType)
{
case enumRoomType.bedroom :
_bedroomVars.bed = 1; break;
case enumRoomType.bathroom :
_bathroomVars.soaps = 2; break;
...
}
}
}
Another option is to inherit Room class for making different room classes
class Room
{
private enumRoomType roomType;
private BedroomVars _bedroomVars;
private BathroomVars _bathroomVars;
public void Room (enumRoomType roomType)
{
this.roomType = roomType;
switch (roomType)
{
case enumRoomType.Bedroom :
_bedroomVars = new BedroomVars; break;
case enumRoomType.Bathroom :
_bathroomVars = new BathroomVars; break;
}
}
public void SomeFunc();
{
switch(RoomType)
{
case enumRoomType.bedroom :
_bedroomVars.bed = 1; break;
case enumRoomType.bathroom :
_bathroomVars.soaps = 2; break;
...
}
}
}
public class BedroomVars : Room
{
bool bed;
int lamps;
}
public class BathroomVars : Room
{
bool tub;
int soaps;
}
I will be very thankful for any help.