Creating a static list from another static list with additional items in C#
March 14, 2021
c#tips-and-tricksWhat
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
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 ๐