In C #, I can initialize a list using the following syntax.
List<int> intList= new List<int>() { 1, 2, 3 };
I would like to know how the {} syntax works, and if it has a name. There is a constructor that accepts IEnumerable , you can call it that.
List<int> intList= new List<int>(new int[]{ 1, 2, 3 });
This seems more "standard." When I deconstruct the default constructor for a list, I only see
this._items = Array.Empty;
I would like to be able to do this.
CustomClass abc = new CustomClass() {1, 2, 3};
And be able to use list 1, 2, 3 . How it works?
Refresh
John Skeet answered
It calls the constructor without parameters, and then call Add:
> List<int> tmp = new List<int>(); > tmp.Add(1); tmp.Add(2); tmp.Add(3); > List<int> intList = tmp;
I understand what I'm doing. I want to know how to do this. How does this syntax know to call the Add method?
Update
I know how to accept John Skeet’s answer. But, the example with strings and ints is awesome. Also a very useful MSDN page is:
Anthony D Apr 15 '09 at 14:34 2009-04-15 14:34
source share