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;
}
}
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With