Add items to a list using an extension method in C# 6

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.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Add items to a list using an extension method in C# 6

  1. 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.

    • Andras Nemes says:

      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

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: