In C# I can initialize a list using the following syntax.
List<int> intList= new List<int>() { 1, 2, 3 };
I would like to how that {} syntax works, and if it has a name. There is a constructor that takes an Ienumerable, you could call that.
List<int> intList= new List<int>(new int[]{ 1, 2, 3 });
That seems more "standard". When I deconstruct the default constructor for the 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 the 1,2,3 list, how does this work?
Update
Jon Skeet answered
It's calling the parameterless constructor, and then calling Add:
> List<int> tmp = new List<int>();
> tmp.Add(1); tmp.Add(2); tmp.Add(3);
> List<int> intList = tmp;
I understand what is does. I want to know how. How does that syntax know to call the Add method?
Update
I know, how cliche to accept a Jon Skeet answer. But, the example with the strings and ints is awesome. Also two very helpful MSDN pages, http://msdn.microsoft.com/en-us/library/bb384062.aspx http://msdn.microsoft.com/en-us/library/bb384062.aspx
Thanks for all your answers!