How would I modify a private list through an external class?

I have a class, let’s call it ‘ClassA’ with a private nested class, let’s call it ‘ClassB’. ‘ClassA’ contains a private instance of ‘ClassB’. Then inside ‘ClassA’ I have a list, so it looks something like this:

class ClassA
{
    ClassB b = new ClassB();
    List l;

    class ClassB
    {

    }
}

My question is how would I give ‘ClassB’ the ability to modify 'ClassA’s private List so that ‘ClassB’ would be able to add and remove items from it? I have tried passing the List into the constructor of ‘ClassB’, since List is a class I figured it would pass by reference and any changes to the List in ‘ClassB’ would also change the list in ‘ClassA’, but that seems to create a new List.

It’s passed by reference, and will be updated. You’re probably doing something else wrong. Code?

1 Like

Passing a reference around is one way.

Another way is to selectively expose public methods.

public class Thing {
    private List<int> privateList = new List<int>();

    public void AddAnInt (int intToAdd){
        if(classFeelsLikeIt){
            privateList.Add(intToAdd);
        } else {
            Debug.Log("Can't be bothered today");
        }
    }
}

This gives you some advantages, you can sanitise data coming in. And you don’t have to expose methods like Clear that might be breaking.

On the other hand any class can access a public method, not just the ones with the reference.

You can get the best of both worlds by wrapping the collection before handing out a reference.

I found the problem. At some point in ‘ClassA’ I clear the list by using ‘list = new List()’, which is what was creating a separate list. I changed it to use the Clear() function instead. Thanks for the help!