This question already has an answer here:
Is it possible to access a parent member in a child class...
class MainClass {
class A { Whatever }
class B {
List<A> SubSetList;
public void AddNewItem(A NewItem) {
Check MasterListHere ????
}
}
List<A> MasterList;
}
So... my main class will have a master list. It will also have a bunch of instances of B. In each instance of B, I want to add new A's to the particular B, but only if they exist in the Master List. I toyed with making the MasterList static and it works ... until I have more than one instance of MainClass... which I will have.
I could pass a reference to MasterList to each instance of B, but I will eventually have multiple of these "MasterLists" and i don't want to have to pass lots of references if i don't have to.
Regardless of whether you nest class B inside class A, any given instance of A will still need to know about the instance of B that it is held by. So you might want to initialize A with a reference to B and keep it in a field. This likely includes un-nesting it.
In C# there is actually no implicit reference to the instance of the enclosing class, so you need to pass such a reference, and a typical way of doing this is through the nested class' constructor.
With your definition, instances of
class B
may access the private methods and static fields ofclass MainClass
.You can use something like this:
Yes, but you would need to have a reference to the instance of MainClass from within you instance of B.
Have you thought of re-working your classes a little bit? Istead of having the AddNewItem method in B, you could have it in MainClass. That way it would be easy to check the MasterList from within MainClass.
This might work for you:
You would then have something in your MainClass to use the method like this:
To summarize it might look something like this: