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)?
The private modifier makes a member of a class visible only within that **class**.Note how it says class, not instance...MemberwiseClone()instead.private[this]) that lets you make a field accessible to only the same instance. (It's the only language I know of that has.)FromX(X x)would be preferable over a 'copy constructor' (just based on my experience in the .NET world, don't have any references or anything).initWithArray.