Jenix Jenix - 1 month ago 12
C# Question

How can I access private members from other classes?

I'm not that new to C# but don't have as much experience as in Java.
As you know, in Java, we can access all the private members from outer classes.
So I tried the same thing in C# because I had some fields and methods needed to be accessed from only inside my plugin library and didn't want it to be shown to users. A simple example can be like this.

public static class StaticClass {

public class InstanceClass {
private int oldValue;
public int Value;
}

public static void Backup(InstanceClass ic) {
ic.oldValue = ic.Value;
}

public static void Restore(InstanceClass ic) {
ic.Value = ic.oldValue;
}
}


If I make the field oldValue public, then it'll be mess and look dirty when end users use the plugin. It doesn't have to be an Inner class or in a some specific form. I just want to know if there is any way to control or access private members of an instance from other static classes in the same assembly only by me.

Answer

For allowing access only within assembly use internal modifier.

public class InstanceClass {
        internal int oldValue;
        public int Value;
    }