Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Is there a way to make the properties of an object in a class non-editable outside the class itself?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading