constructor - C# new operate bug? -
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 know value of listtest.mylist
?
it {1,2,3,4,5,6}
someone can explain that??
it's not bug, consequence of how { ... }
initializer syntax works in c#.
that syntax available collection type has add()
method. , replace sequence in braces sequence of calls add()
method.
in example, first initialize, in constructor, value first 3 elements. then, later when assign { 4, 5, 6 }
property, calls add()
again values.
if want clear previous contents, need assign new
operator, this:
var listtest = new listtest() { mylist = new list<int> {4,5,6} };
by including new
operator, both whole new object, add()
values.
Comments
Post a Comment