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();
}
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With