Christoph,
Private members of a class are meant to be accessed by other members of the
class. if privateVar is inaccessible by methods with its class, virtually
nothing can ever touch it. Now this doesn't make sense since anything in a
program must be used somewhere.
When we decide the accessibility of a member within a class we are looking
at a class-scope. That is, if a member is declared private, it is private to
THE CLASS so that it makes pretty good logic that the other members within
the same class should have a right to access the (private) member. Your
constructor MyClass.MyClass() actually implicitly initiates the privateVar
member without you writing a line of code.
A well designed class must maintain a proper degree of encapsulation. If
something is not meant to be used by its client then by all means make it
private. If somehow something is not meant to be used by the client but
making it private will cause the class exceedingly difficult to reuse, make
it protected.
ben
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