public class ListTest
{
public List<int> MyList;
public ListTest()
{
MyList = new List<int> { 1, 2, 3 };
}
}
var listTest = new ListTest()
{
MyList = {4,5,6}
};
Do you know the value of listTest.MyList
?
It would be {1,2,3,4,5,6}
Someone can explain that??
It's not a bug, but a consequence of how the { ... }
initializer syntax works in C#.
That syntax is available for any collection type that has an Add()
method. And all it does is replace the sequence in the braces with a sequence of calls to the Add()
method.
In your example, you first initialize, in the constructor, the value with the first three elements. Then, later when you assign the { 4, 5, 6 }
to the property, that calls Add()
again with those values.
If you want to clear the previous contents, you need to assign with the new
operator, like this:
var listTest = new ListTest()
{
MyList = new List<int> {4,5,6}
};
By including the new
operator, you get both a whole new object, as well as the Add()
values.
var listTest = new ListTest() // This line will first call constructor of ListTest class .
//As constructor adds 1,2,3 in list MyList will have 3 recrods
{
MyList = {4,5,6} // Once you add this statement this will add 3 more values in the list .
// So instead of creating new list it will Add 3 elements in existing list
};
//Hence total 6 records will be there in the list
This syntax simply calls .Add
after constructor finished. As result you get 1,2,3 from constructor and than 4,5,6 added one by one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With