How private are private fields?

The other day when I was working on creating a object/assembly browser for the web I was thinking about the power of reflection.  Using reflection you can get access to any any part of a class including private members.  So I wrote a simple project to test and see I could change private fields using reflection, or call private methods using reflection.

class MainClass
{
  static void Main(string[] args)
  {
    NotPrivate test1 = new NotPrivate();
    Console.WriteLine("[test1]TestInt = " + test1.TestInt);
    FieldInfo fi = test1.GetType().GetField("testInt", BindingFlags.Instance | BindingFlags.NonPublic);
    fi.SetValue(test1, 3);
    Console.WriteLine("[test1]TestInt = " + test1.TestInt + " after setting private field");

    NotPrivate test2 = new NotPrivate();
    Console.WriteLine("[test2]TestInt = " + test2.TestInt);
    MethodInfo mi = test2.GetType().GetMethod("SetTestInt", BindingFlags.Instance | BindingFlags.NonPublic);
    mi.Invoke(test2, new object[]{3});
    Console.WriteLine("[test2]TestInt = " + test2.TestInt + " after calling private method SetTestInt");
  }
}

public class NotPrivate
{
  private int testInt = 2;

  public int TestInt
  {
    get { return testInt; }
  }
    
  private void SetTestInt(int i)
  {
    testInt = i;
  }
}
Output:
[test1]TestInt = 2
[test1]TestInt = 3 after setting private field
[test2]TestInt = 2
[test2]TestInt = 3 after calling private method SetTestInt
 
So using reflection I was able to successfully change a private field and sucessfully able to call a private method.  So does reflection possibly give us to much power?  This means using any class/assembly browser we can get the private field/method/property/etc and use reflection to manipulate it.
 

2 Comments

  • LOL.





    Private fields are still accessible within the same namespace. The thing is to try it from a separate assembly, or defining a different namespace. It may still be accessible because it is in the same application domain.

  • This is handled by the security policy. By default, your local code has full ReflectionPermission (which is why you can see those private members), while code from the Internet Code Group, for example, has none. You can administer this with caspol.exe

Comments have been disabled for this content.