Add items to a list using an extension method in C# 6
February 18, 2016 2 Comments
C# 6 introduces a new way of filling up collections with objects.
Consider the following Rockband class:
public class Rockband { public string Name { get; } public int NumberOfMembers { get; } public Rockband(string name, int numberOfMembers) { Name = name; NumberOfMembers = numberOfMembers; } }
Next we want to build a list of rockbands and add a couple of items to it during initialisation:
List<Rockband> rockbands = new List<Rockband>() { new Rockband("Queen", 4), new Rockband("Genesis", 5), new Rockband("Metallica", 4) };
That should be pretty straightforward.
We can make that code shorter and adding the items less tedious by an extension method on a List of Rockband objects. The extension method must be called “Add” and must accept the input parameters necessary for object construction:
public static class Extensions { public static void Add(this List<Rockband> rockbands, string name, int numberOfMembers) { rockbands.Add(new Rockband(name, numberOfMembers)); } }
The list initialisation can now be shortened to the following:
List<Rockband> rockbands2 = new List<Rockband>() { { "Queen", 4 }, { "Genesis", 5 }, { "Metallica", 4 } };
We can even use the Add method to filter out unwanted elements. Let’s say that we only accept rock bands with at least 5 members:
public static class Extensions { public static void Add(this List<Rockband> rockbands, string name, int numberOfMembers) { if (numberOfMembers > 4) { rockbands.Add(new Rockband(name, numberOfMembers)); } } }
Only Genesis will be added to the list in this case. Mind you, we’re talking about the original 5-man line-up, not the more modern one with only 3.
View all various C# language feature related posts here.
I still haven`t seen C#6 specs, so your posts are so interesting for me. Thanks, Andras.
For earlier C# versions for same result a chain of Add() may be used:
public static List rockbands Add(this List rockbands, string name, int numberOfMembers)
{
if (numberOfMembers > 4)
{
rockbands.Add(new Rockband(name, numberOfMembers));
}
return rockbands;
}
…
…
List rockbands2 = new List()
.Add(“Queen”, 4)
.Add(“Genesis”, 5)
.Add(“Metallica”, 4);
Although, not as handy as your example.
Thanks for your comment. I’ve only recently started checking out the new stuff in C# 6. There are no groundbreaking novelties, like LINQ in .NET 4 or await-async in .NET4.5, it’s more about smaller additions and extensions as far as I can see.
//Andras