I tried merging a collection definition with a collection initializer in C#, but failed to initialize the collection. See the codes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ListEX : MonoBehaviour
{
public List<string> sList = new List<string>()
{
"A", "B", "C", "D",
};
void Start()
{
sList.Add("X");
sList.Add("Y");
string str = "";
foreach (string i in sList)
{
str += i;
}
print(str);
}
The output of str was "XY" instead of "ABCDXY", which confuzed me a lot. The same problem happened to arrays and dictionaries when I tried them out.
I assume I made a mistake in the scope of the collection initializer. So, I tried separating the collection initializer from the collection definition.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ListEX : MonoBehaviour
{
public List<string> sList;
void Start()
{
sList = new List<string>()
{
"A", "B", "C", "D",
};
sList.Add("X");
sList.Add("Y");
string str = "";
foreach (string i in sList)
{
str += i;
}
print(str);
}
The output of str was "ABCDXY", which met my expectation. My thought seems to be proved right. However, I cannot still explain the principle of how C# works with this.
I'd appreciate it if someone can give me an explanation.
This is a Unity MonoBehaviour script, by default public fields (
sListin this question) can be edited in a window called inspector, the values of these fields will be deserialized on initial, C# has nothing todo with it, that's why you get an empty list whenStartruns.If you want to test the collection initializer and avoid being affected by serialization, you can change the access modifier to private, or use the
NonSerializedattribute.BTW the same problem should not happen to
Dictionary<K,V>because it is not a serializable type to Unity, if there is a problem with the dictionary type, please provide the code with the problem.