Question on access modifiers

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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.
 
Flack said:
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?

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);
}
}
}
 
Back
Top