This question already has an answer here:
-
What's the best way of accessing field in the enclosing class from the nested class?
8 answers
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.
You can use something like this:
class B {
private MainClass instance;
public B(MainClass instance)
{
this.instance = instance;
}
List SubSetList;
public void AddNewItem(A NewItem) {
Check MasterListHere ????
}
}
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 of class MainClass
.
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.
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:
public void AddNewItem(A newItem, Func<A, bool> checkForItemInMasterList)
{
if (checkForItemInMasterList.Invoke(newItem)
SubList.Add(newItem);
}
You would then have something in your MainClass to use the method like this:
public void AddItem(A newItem)
{
new B().AddNewItem(newItem, x => MasterList.Contains(x));
}
To summarize it might look something like this:
class MainClass {
class A { Whatever }
class B {
List<A> SubSetList;
public void AddNewItem(A newItem, Func<A, bool> checkForItemInMasterList)
{
if (checkForItemInMasterList.Invoke(newItem)
SubList.Add(newItem);
}
}
//I don't know how you're adding items to instances of B.
//This is purely speculative.
public void AddItem(A newItem)
{
new B().AddNewItem(newItem, x => MasterList.Contains(x));
}
List<A> MasterList;
}