C
Christoph Boget
Let's take the following class:
class MyClass {
private int privateVar;
public int PublicVar {
get { return privateVar; }
}
public MyClass() {}
public MyClass Test() {
MyClass myClass = new MyClass();
myClass.privateVar = 99;
return myClass;
}
}
How is it that in the Test() method, my newly instantiated
'myClass' variable can access the private 'privateVar' member?
Because the code is executing within a method of the 'MyClass'
class? Shouldn't it be that an object cannot access private
members regardless of where it's executed? Now, that is
true if I try to execute that exact same code in a method of
another class which is as it should be. I'm just curious what
is it that's telling both the compiler and the CLR that accessing
the private member in the above method is alright.
thnx,
Christoph
class MyClass {
private int privateVar;
public int PublicVar {
get { return privateVar; }
}
public MyClass() {}
public MyClass Test() {
MyClass myClass = new MyClass();
myClass.privateVar = 99;
return myClass;
}
}
How is it that in the Test() method, my newly instantiated
'myClass' variable can access the private 'privateVar' member?
Because the code is executing within a method of the 'MyClass'
class? Shouldn't it be that an object cannot access private
members regardless of where it's executed? Now, that is
true if I try to execute that exact same code in a method of
another class which is as it should be. I'm just curious what
is it that's telling both the compiler and the CLR that accessing
the private member in the above method is alright.
thnx,
Christoph