Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why private members of a class instance are getting available in Equals() method body? [duplicate]

Tags:

c#

.net

oop

clr

equals

Possible Duplicate:
Why are my privates accessible?
Why are private fields private to the type, not the instance?

Most probably I am missing an obvious fact but I cannot really see the reason:

When I override the Equals() method and when I cast the object to my type, I am able to call its private members without any problem!!!

I am initializing an instance and I expect its private members not to be reachable.

But why the casted object opens its privates to me in the Equals() method?

See the Equals implementation on the sample code below and see how I am reaching the private fields on the "that" instance:

 public class Animal
 {
     private string _name;
     private int _age;

     public Animal(int age, string name)
     {
         _name = name;
         _age = age;
     }

     public override bool Equals(object obj)
     {
         var that = (Animal) obj;


         //_name and _age are available on "that" instance
         // (But WHY ??? )
         return
             this._age == that._age
             && this._name == that._name; 

     }
 }


    class Program
    {
        static void Main(string[] args)
        {
            var cat1 = new Animal(5, "HelloKitty");
            var cat2 = new Animal(5, "HelloKitty");

            Console.Write(cat1.Equals(cat2));
            Console.Read();
        }
    }
like image 946
pencilCake Avatar asked Sep 06 '11 14:09

pencilCake


1 Answers

Private members are private to a class, not to an instance.

Inside the Animal class, you can access any private members of any instance of Animal that you are passed (or, in this case, successfully cast to).

like image 54
Justin Niessner Avatar answered Oct 29 '22 00:10

Justin Niessner