Search code examples
c#classfriendaccess-modifiers

Accessing protected members of another class


I have one class A, from which I need to access protected members of class B, in the same manner that one would use the friend keyword in C++. However, the internal modifier does not suit my needs. Class B will need to create an instance of class A, modify its private data, and return a reference to that class. Those class A members will need to remain private to the original caller.

public class A
{
    protected int x;
}

public class B
{
    public static A CreateClassA()
    {
        A x = new A();
        x.x = 5;   // ERROR : No privilege
        return x;
    }
}

Solution

  • You will need to either create a public setter for the protected field or inherit from the class.

    public class A
    {
        protected int x;
    
        public int X { set { x = value; }  }
    }
    
    public static A CreateClassA()
    {
        A x = new A();
        x.X = 5;
        return x;
    }
    

    Or:

    public class B : A
    {
        public static A CreateClassA()
        {
            this.x = 5; 
            return x;
        }
    }