A shorter way to initialize Lists in C#

Threre is a trick that I wanted to show you today. A trick you can do initialize your lists a bit easier. Of course there’s some plumbing to be done.

Let’s assume you have a class definition like the following.

public class Foo
{
    public int A { get; set; }
    public int B { get; set; }
    public int C { get; set; }
    void Foo(int a, int b, int c)
    {
        A = a;
        B = b;
        C = c;
    }
}

You would typically initialize a list of Foo type like the following.

var foos = new List<Foo>();
foos.Add(new Foo(1, 2, 3));
foos.Add(new Foo(4, 5, 6));
// and more ...

But if you write and extension method like below.

public static class FooExtensions
{
    public static void Add(this IList<Foo>  list, int a, int b, int c) => list.Add(new Foo(a, b, c));
}

You can initialize your list like so:

var foos = new List<Foo>
{
    {1, 2, 3},
    {3, 4, 5},
    {6, 7, 8},
    // and more ...
};
A shorter way to initialize Lists in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.