L.Tim
L.Tim

Reputation: 61

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??

Upvotes: 5

Views: 117

Answers (3)

Ankit
Ankit

Reputation: 6153

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

Upvotes: 4

Peter Duniho
Peter Duniho

Reputation: 70691

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.

Upvotes: 14

Alexei Levenkov
Alexei Levenkov

Reputation: 100545

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.

Upvotes: 3

Related Questions