Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 648
user1364556 Avatar asked Nov 17 '25 20:11

user1364556


2 Answers

The question is a bit old at this point but here's another method, doing what you ask, without lectures or finger-wagging:

Consider:

A foo = new A();
FieldInfo privateField = foo.GetType().GetField("x", BindingFlags.NonPublic | BindingFlags.Instance);
privateField.SetValue(foo, 5);

Warning: Use of the above code breaks encapsulation, curves your spine and may cause ear damage from the shrill screaming of OO purists.

...but it works great for factory classes, compensating for C#'s lack of a friend keyword.

Warning 2: This is slow.

like image 121
Joshua Pech Avatar answered Nov 19 '25 09:11

Joshua Pech


You can use protected internal instead of internal to give access to all classes in the same assembly, as well as subclasses in other assemblies:

public class A
{
    protected internal int x;
}

public class B
{
    public static A CreateClassA()
    {
        A x = new A();
        x.x = 5;   // hurray
        return x;
    }
}