Possible Duplicate:
Why and how does C# allow accessing private variables outside the class itself when it’s within the same containing class?
This has completely passed me by some how, apparently the code below is legal, and more surprising is legal from framework 2 onwards…
public class Magic
{
private readonly int _anInt;
private readonly string _aString;
public Magic(int anInt, string aString)
{
_anInt = anInt;
_aString = aString;
}
public Magic(Magic toCopy)
{
_anInt = toCopy._anInt; // Legal!
_aString = toCopy._aString; // Legal!
}
public void DoesntWorkMagic(Magic toCopy)
{
_anInt = toCopy._anInt; // edit: Will work if not readonly.
_aString = toCopy._aString;
}
public int AnInt { get { return _anInt; } }
public string AString { get { return _aString; } }
}
What’s going on? I’ve seen so many copy constructors doing excess work over the years, I wouldn’t have believed this work until I came across it. Are there any caveats to its use (besides the obvious threading issues)?
private is not object level, it is class level, so objects of the same class know about their private aspects, so are allowed to change private things on other object of the same class.
private prevents other types poking around where they shouldn’t go.