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}

enter image description

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

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -