Search code examples
c#propertiesaccess-modifiers

Can I create a property in a struct with a "set" only accessible by a single concrete class?


I know it sounds a bit weird, but I will try to explain it: suppose I have a class with a lot of properties, and all of them are read-only, so this class is the only one which can modify its properties (it is listening to an event, and fills the properties with the information contained on that event).

But, I want to encapsulate some of the properties on some structs, to create a well organized hierarchy, so these structs'properties should be read-only too, except for the owner class. For example:

public class A
{
    private int a1;
    public int A1 
    { 
        get{ return a1; } 
    }

    private B structB;
    public B StructB
    {
        get{ return structB; }
    }

    private method eventListenerMethod(...)
    {
        a1 = someValue;
        structB.B1 = otherValue; //I want that only this class can modify this property!
    }
}

public struct B
{
    private int b1;
    public int B1
    {
        get{ return b1; } // This property should be modifiable for Class A!!
    }
}

I think I cannot do that, but does anyone know how can I achieve it? Thank you very much in advance.


Solution

  • Seems what you're after is the "friend" keyword in C++. However, it doesn't exist in C#, but "internal" is a good compromise. So, just make a "internal set" property, which'll be accessible (only) within the assembly. So other people who'll use your assembly won't have access to it