Empty anonymous collections in C#

Sometimes I think too hard

March 3, 2018

This week I had a need to create an empty list with groups of three items (name, customer number, external entity id) in one place in a method, and use it further down in the same method. This is transient data used only in this single method. Since I am only using it in one place, creating a class or struct seemed like overkill. (And yes, it probably indicates a refactor is necessary, but stay with me, la la la can’t hear you).

My first thought was to use a tuple:

var x = new List<Tuple<string, long, int>>();
x.Add(new Tuple<string, long, int>("Jones, David", 12345, 1));

Of course the problem with that is while it is strongly typed, the names when I consume it later are Item1, Item2 and Item3. Not too meaningful.

OK, then I can use dynamic, and give it meaningful names when I add an item to the list

var y = new List<dynamic>();
y.Add(new { name = "Jones, David", custno = 12345, entityid = 1 });

The problem with that is then I don’t get strong typing, so if I mistype one of the member names when I am accessing it later, I won’t know until run-time. Not good.

This then came to me. It works just dandy, and gives me an empty list of the appropriate type with both meaningful member names and strong typing:

var z = (from x in new List<int>() select new { name = "", custno = 0L, entityid = 0 }).ToList();
z.Add(new { name = "Jones, David", custno = 12345, entityid = 1 });

Because it is selecting from an empty list, it creates an empty list, but strongly typed exactly as I need it! Cool? Or horrifying?

Strongly-typed empty anonymous collection
Strongly-typed empty anonymous collection