KAJAN M

Creating a static list from another static list with additional items in C#

March 14, 2021

c#tips-and-tricks

What


As the heading says, this post is regarding creating a new static list based on another static list with some additional items in a single statement.

Time to time, I had this requirement, but I couldnโ€™t figure out a way then. Recently, I accidentally* came across a solution. Iโ€™m documenting it hoping someone might find it useful.

*My IDE(JetBrains Rider) helped while experimenting with different approaches ๐Ÿ˜›. Thank you JetBrains people!

Table of Contents


  • What
  • Use case
  • The problem
  • Alternative approaches
  • Solution
  • Summary

Use case


The main use case is, say weโ€™ve a bunch of statuses in a static list that we use to filter data. Now, in another part of the system, we want to filter based on that existing list items, but with some more statuses.

The problem


Since the initialization is done in a static class, we canโ€™t just create the list in one statement and add items later as we do normally, right?

Alternative approaches


I used to create a non-static list as needed. While this works, I think defining a new static list is more appropriate. That way, we can save some CPU cycles in instantiating new instance and garbage collecting it. Hmmm, this sounds an over-engineered argument โ€” but the solution is simple, so why not use it?

We can also create a new static list separately independent of the first list but, Iโ€™m sure, there are situations that demand relying on the first list.

Solution


So, the idea is to combine constructor initialization with object initialization syntax. Below is a code example for your reference.

using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace StaticList
{
public static class OfficerStatuses
{
public enum OfficerStatus
{
Pending,
Accepted,
DeploymentCommenced,
Resigned,
Blacklisted
}
public static readonly ReadOnlyCollection<OfficerStatus> InactiveOfficerStatuses = new List<OfficerStatus>
{
OfficerStatus.DeploymentCommenced,
OfficerStatus.Resigned,
OfficerStatus.Blacklisted
}.AsReadOnly();
public static readonly ReadOnlyCollection<OfficerStatus> OfficerStatusesToHide =
new List<OfficerStatus>(InactiveOfficerStatuses)
{
OfficerStatus.Pending
}.AsReadOnly();
}
}

Summary


Creating a new list(array) from another one with additional entries in a single call is dead simple in JavaScript. Well, now we know that is the case in C# as well ๐Ÿ˜‰


Kajan
๐Ÿ‘‹ Hi! Welcome to my blog. I'm Kajan, a Software Engineer focusing on ASP.NET Core, EF Core and JavaScript(Vue, React) stack. I am thankful to the internet community for helping me out on various occasions ๐Ÿ™๐Ÿ˜˜. I hope to give back to the community by sharing my experience, and knowledge.
Twitter
GitHub