Thursday, 25 January 2007

when is private not private?

Note: The RichText blog has moved to

If a method within a class is marked as 'private', one might expect that it is only accessible from inside of that instance. Well, you'd be wrong (at least you would in C# - and I assume the rest of Microsoft.NET too).

In C#, if you define a member as private, then it is indeed accessible only to that class. However, it isn't restricted to only that instance: Any instance of that type can access the private members of another instance of the same type. This is a bit counter intuitive to me, and freaked me out a bit when I first saw it, as it seems to break encapsulation! Try it if you don't believe me.

Ruby has a different approach, and one which goes some way towards placating my OO-purist tendencies. As you'd expect, public methods can be called by anyone. Protected methods can be invoked only by objects of the defining class and its subclasses (ANY instance of the defining class). Private methods can only be called in the current object's context. i.e. you can't invoke another object's private methods, no matter what it's type.

Digg Technorati Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

1 comment:

rasional said...

can u give the sample code .. do you mean using reflection?

sorry iam beginner..