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 ...
};
Leave a Reply