C # new work error?

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 will be {1,2,3,4,5,6}

enter image description

Can someone explain what ??

+5
source share
3 answers

This is not an error, but a consequence of how the initializer { ... } syntax works in C #.

This syntax is available for any type of collection that has the Add() method. And all he does is replace the sequence in braces with the sequence of calls to the Add() method.

In your example, you first initialize the value with the first three elements in the constructor. Then, later, when you assign the property { 4, 5, 6 } property that calls Add() again with these values.

If you want to delete the previous contents, you need to assign a new operator, for example:

 var listTest = new ListTest() { MyList = new List<int> {4,5,6} }; 

By including the new operator, you get both the whole new object and the Add() values.

+13
source
 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 
+3
source

This syntax simply calls .Add after the constructor completes. As a result, you get 1,2,3 from the constructor and 4,5,5 are added one after another.

+2
source

Source: https://habr.com/ru/post/1271024/


All Articles