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.
Start()method? How do you call it anyway since it is marked as private? Maybe you call asList.Clear()before you callStart()Start()is a method that's there by convention, and seemingly called through reflection: docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html