Privacy of a class

I thought it is never possible to access the fields which are declare as private, so i wonder as i first saw this code compiling.

    public class Person
        private int height;

        private void grow() 
            height += 10; 

        public Person(Person person)
            person.height = 10;

After some seconds of thinking about the basics of object oriented programming it makes sense. The private fields and methods can be used inside of the class also if it is not the same object you access. The class, or in another point of view the object, already knows how the private fields and methods should be used. The same for static methods, like a comparer inside the person class, which takes two person objects as input. I have used this several times in static methods, but never spend a minute thinking about it. The C# Language specification tells us for private: Access limited to the containing type!

Naturally it also work in partial class, because at the end it is the one class and so the same type. Otherwise in extension methods can’t access the private fields and methods of the extended class. Extension methods exists outside the class which it extends, so it doesn’t belong to the same type.

One thought on “Privacy of a class

  1. I’ve been reading your posts for the last couple of hours, and it all may be very informative and well written. I did want to allow you know that for some reason this post doesn’t seem to work in Internet Explorer. On a side note, I had been wondering if you desired to swap blogroll links? I hope to hear from you soon!

Comments are closed.