I am looking for a way to have an object in a class and make it non-editable (the object itself AND its properties) outside the class itself but still visible outside.
internal class Room
{
public string Description { get; set; }
}
internal class RoomController
{
public Room Room { get; private set; }
public RoomController()
{
Room = new Room();
}
//Edit the room inside this class
}
internal class Foo
{
public void SomeMethod()
{
RoomController rc = new RoomController();
rc.Room.Description = "something"; // This should not be allowed
string roomDesc = rc.Room.Description; // This should be fine
}
}
Is something like that possible? I couldn't find anything regarding the issue so I would be grateful if anyone has any ideas.
Thanks in advance!
CodePudding user response:
You could define an interface that only exposes the bits you want public:
internal interface IReadonlyRoom
{
string Description { get; } //note only getter exposed
}
internal class Room : IReadonlyRoom
{
public string Description { get; set; }
}
internal class RoomController
{
private Room _room;
public IReadonlyRoom Room => _room;
public RoomController()
{
_room = new Room();
}
//edit using _room
}