Dialock
Dialock

Reputation: 263

How might a List<T> be reset?

I have an object I create and stick in a collection:

public class Level
{
    private string id;

    private List<LevelTypes> usableLevelTypes;  // LevelTypes is an enum
    private List<BlockTypes> levelMapping;      // BlockTypes is also an enum

    public Level(string id, List<LevelTypes> levelTypes, List<BlockTypes> incomingBlocks)
    {
        this.id = id;
        this.usableLevelTypes = levelTypes

        levelMapping = incomingBlocks;
    }

Stepping through this, I can see each item being set properly. The object is then placed in a HashSet.

Another class then iterates through the HashSet calling each item's overloaded .ToString() method.

At this point I have all relevant variables in this class on my watch list. Everything within the object called is set properly. "id", "levelMapping" and all other variables that I have not listed including other List<T>'s and int's contain their proper values except "usableLevelTypes", which is reported as being empty.

public override string ToString()
{
    var s = new StringBuilder();

    s.Append("ID: " + id);
    s.Append(" Level Types: " + usableLevelTypes[0].ToString()); // At this point,
    // this list should have at minimum one value in it.  However, it is empty and
    // will throw an exception stating as much.

    return s.ToString();
}

At no point is .Clear() called on the usableLevelTypes List and it is read-only. How could it be reset when other lists within the same object are not?

Upvotes: 0

Views: 358

Answers (1)

siride
siride

Reputation: 209495

You are not creating a copy of the list that you pass in to the Level constructor for usableLevelTypes. So whatever is happening to that outer list is going to happen to the list inside Level. Without seeing the calling code, I cannot tell you specifically what the problem is.

Upvotes: 1

Related Questions