Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# class members access issue

class A
{
    public int x { get; set; }
    // other properties
}

class S
{
    public A GetA(...);
}

I would like to make the following restriction:
A can be only modified inside S. When someone else get A via GetA(), he can only get A's properties, not modify them.

I decided to make a new function in S that returns another object:

class B
{
    A a;
    public int x { get { return a.x; } }
    // replicate other A's properties
}

Is there a better solution?

like image 993
Ivan Avatar asked Feb 15 '23 13:02

Ivan


1 Answers

You could make an interface of A with only the getters defined, and return that from GetA:

public interface IA
{
   int x { get; }
}

class A : IA
{
    public int x { get; set; } // nothing stopping you having a setter on the class
}

class S
{
    private A a = new A(); // you can call the setter internally on this instance
    public IA GetA(){ return a; } // when someone gets this thy only get the getter
}

Of course, there's nothing stopping someone casting the result of GetA to A and then they have the setter - but there's really nothing you can do about that!

like image 79
Jamiec Avatar answered Feb 24 '23 17:02

Jamiec