Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 you know the value of listTest.MyList?

It would be {1,2,3,4,5,6}

enter image description

Someone can explain that??

like image 884
L.Tim Avatar asked Aug 20 '17 05:08

L.Tim


3 Answers

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.

like image 152
Peter Duniho Avatar answered Sep 28 '22 11:09

Peter Duniho


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
like image 35
Ankit Avatar answered Sep 28 '22 11:09

Ankit


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.

like image 40
Alexei Levenkov Avatar answered Sep 28 '22 13:09

Alexei Levenkov