0

When I reorder a list by adding a value, a dictionary with the same value type updates.

Here is the code that I used. After swapping the order of lst in the Unity inspector, "dict["daveID"].name" displays "Jessica".

public class Check : MonoBehaviour
{

    Dictionary<string, Person> dict = new Dictionary<string, Person>();
    [SerializeField] List<Person> lst = new List<Person>();

    private void Start()
    {
        dict.Add("daveID", new Person("Dave"));
        dict.Add("jessID", new Person("Jessica"));

        foreach (var i in dict)
        {
            lst.Add(i.Value);
        }
    }

    private void OnGUI()
    {
        GUILayout.Label("daveID's string (dct): " + dict["daveID"].name + " lst version: " + lst[0].name);
    }
}

[System.Serializable]
public class Person
{
    public string name;

    public Person(string name)
    {
        this.name = name;
    }
}

My question is, why is the list and dictionary linked like this?

Update

I have edited my question for clarity. I understand that the objects are references, but surely reordering a list will not affect a dictionary's key/value pairs.

  • _"why is the list and dictionary linked like this?"_ - because they're reference-types: https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c – Dai May 05 '23 at 01:23
  • ...you are adding the *same objects* to the list. you are not creating `new` ones – Ňɏssa Pøngjǣrdenlarp May 05 '23 at 01:24

0 Answers0