Hello,
Lets say I have this class definition:
public class Class1
{
private int _privInt = 2;
protected int _protInt = 4;
public void SomeMethod(Class1 class1_)
{
System.Diagnostics.Debug.WriteLine(class1_._privInt);
System.Diagnostics.Debug.WriteLine(class1_._protInt);
}
}
I have defined a private int field and a protected int field. Since those
fields have restricted access, how come I can access them in SomeMethod
without any issues? I would think that since _privInt is private to the
Class1 class, specifically the method parameter class1_, I wouldn't be able
to access it.
Can any private field of a class be readily accessed from within the
definition of that class, regardless of which instance of the class you are
using?
Thanks.
Jon Skeet [C# MVP] - 20 Jun 2007 23:19 GMT
> Lets say I have this class definition:
>
[quoted text clipped - 19 lines]
> definition of that class, regardless of which instance of the class you are
> using?
Yes - indeed, that's pretty much the definition of it. Various things
would be harder without that model.
What you might find peculiar is that the actual definition of the
accessibility is based on "program text", not on the type itself.
That means that private members of an enclosing type are accessible to
nested types too:
using System;
class Test
{
private static int x;
static void Main()
{
x = 10;
new Nested();
}
class Nested
{
public Nested()
{
Console.WriteLine(Test.x);
}
}
}

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too