Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick way to turn object into single-element list?

Tags:

c#

list

.net-2.0

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?
like image 375
CJ7 Avatar asked Dec 27 '22 12:12

CJ7


1 Answers

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.

like image 183
phoog Avatar answered Jan 07 '23 04:01

phoog