I have this simple code:
public static void Main(String[] args)
{
Data data = new Data { List = { "1", "2", "3", "4" } };
foreach (var str in data.List)
Console.WriteLine(str);
Console.ReadLine();
}
public class Data
{
private List<String> _List = new List<String>();
public List<String> List
{
get { return _List; }
}
public Data() { }
}
So when I'm creating a Data class:
Data data = new Data { List = { "1", "2", "3", "4" } };
The list was filled with strings "1", "2", "3", "4" even if it had no set
.
Why is this happening?
List string2
and then you are readingList string1
makes no sense to me. – AbyList string2
anywhere in your code. – Abystring2
must be empty. – WiltonwiltseyAdd
which uses theget
– Abyreadonly
is a keyword (in your new title) that doesn't appear anywhere in the code and doesn't appear to be related to the question in any way. Was this intended? (It also makes all references tostring1
andstring2
in the comments and answers nonsensical.) – Basidium