More on privates...

Wes asked exactly how private is private this past week, showing how reflection can be used to modify private fields and invoke private methods.

After giving it some thought, and discussing it with a few colleagues, I guess we can consider access modifiers not a security feature so much as a way to encapsulate internal implementation details. And sure, the general assumption is that anything in memory is never really "private", because someone somewhere can always touch it. But I still have a tough time getting my head around this, because it kind of violates a lot of what you're taught from day one when it comes to OOP.

Then again, I should be used to this, after all the crazy Javascript I've done over the past two years. Javascript is really powerful in this regard - if powerful is the right word. Not only does Javascript have no means to enforce access modifiers, it allows you to change an instance's composition at runtime. Hell, you can even mess with an object's prototype, effectively modifying any new instances of that object.

This should also teach us, I guess, that we can't take the validity of private fields for granted. For example, if the only place we're doing validation is in a property modifier, it leaves the door open to potential, unexpected behavior.

I expanded on Wes' original example a little, and using a built-in .NET type instead of using a custom class.

string s = "test"; t = s.GetType();
FieldInfo[] fields = t.GetFields( BindingFlags.Instance | BindingFlags.NonPublic );
foreach (FieldInfo field in fields)

{
   if (field.IsPrivate && field.FieldType == typeof(int))
   {
      field.SetValue(s,3000);
   }
}
Console.WriteLine(s);

Now, bear in mind I don't know much (read: anything) about buffer overflows or how the CLR handles memory and so on (maybe it's time to get that book sooner than I thought), but it seems like this could be bad. Would it be possible, for example, to touch other AppDomains (on shared ASP.NET hosting) with this, or even worse, to break out of the .NET sandbox?

EngineeringWriting