What is the quickest in C# 2.0
to create a one-element list out of a single object?
eg:
MyObject obj = new MyObject();
List<MyObject> list = new List<MyObject> { obj }; // is this possible?
Your sample code
List<MyObject> list = new List<MyObject> { obj };
uses a collection initializer, which was not available in C# 2.0. You could use an array initializer, instead:
List<MyObject> list = new List<MyObject>(new MyObject[] { obj });
Or, just make the list and add the object:
List<MyObject> list = new List<MyObject>(1);
list.Add(obj);
Note that "singleton" usually refers to the singleton pattern; as you see from the comments, it's confusing to use that term to refer to a collection containing one element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With