Reputation: 11972
If I create a private nested class, how can I access the variables and methods from the calling class?
Example:
public class ClassA
{
protected int MyVar=100;
public MethodA()
{
// <some code>
myObjectClassB.DoSomething();
// <some code>
}
private class ClassB
{
public DoSomething()
{
}
}
}
In the above example I need ClassB to be able to access ClassA.MyVar - Is this possible?
Upvotes: 0
Views: 65
Reputation: 8780
Ok Dan Bryant beat me to it, except he forgot to add that you'll have to make that protected variable internal in order to access it. A nested class is no different than ANY other class that's not nested except for the naming convention. It doesn't get any special priveledges to the class it's nested in. It's purely an organizational thing to nest.
Edit: Okay, maybe I'm wrong about that. I actually read the rest of Dan's answer after this and it seems perhaps I was mistaken :)
Edit 2: After a couple searches I found that I was not entirely incorrect in my thinking, but it just depends on which compiler you're working with. Older C++ specification did not allow it, but most compilers allowed it anyway and eventually they changed the docs to reflect what was actually happening in the compilers.
Upvotes: 0
Reputation: 27495
When you construct an instance of ClassB, give it a reference to the ClassA that owns it.
private class ClassB
{
private readonly ClassA _owner;
public ClassB(ClassA owner)
{
_owner = owner;
}
public DoSomething()
{
}
}
One interesting thing to note about this is that the private nested class can actually access private members of ClassA through _owner. This often comes in handy when you have an internal helper class that needs access to the overall private state of the class.
Upvotes: 2