Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a constant hashset in c# [duplicate]

Tags:

c#

hashset

Right now I have a const array of strings and loop through to check if a value exists. But I want a more efficient way to store my values. I know there's a hashset which I can use like so:

HashSet<string> tblNames = new HashSet<string> ();
tblNames.Add("a");
tblNames.Add("b");
tblNames.Add("c");

However, is it possible to make this a constant member of my class like this:

public const HashSet<string> tblNames = new HashSet<string>() { "value1", "value2" };
like image 883
DannyD Avatar asked Oct 26 '25 16:10

DannyD


1 Answers

The best way to create a 'constant' Set is probably by exposing your HashSet as its IEnumerable interface, using the following:

public static readonly IEnumerable<string> fruits = new HashSet<string> { "Apples", "Oranges" };
  • public: everyone can access it.
  • static: there's only going to be one copy in memory, no matter how many instances of the parent class is created.
  • readonly: you can't re-assign it to a new value.
  • IEnumerable<>: you can only iterate through its contents, but not add/remove/modify.

To search, you can use LINQ to call Contains() on your IEnumerable, and it is smart enough to know it's backed by a HashSet and delegate the proper call to utilise the hashed nature of your set. (well, ok, it calls it via ICollection, but ends up in HashSet's overridden method anyway)

Debug.WriteLine(fruits.Contains("Apples")); // True
Debug.WriteLine(fruits.Contains("Berries")); // False

fruits = new HashSet<string>(); // FAIL! readonly fields can't be re-assigned
fruits.Add("Grapes"); // FAIL! IEnumerables don't have Add()
like image 197
NPras Avatar answered Oct 28 '25 07:10

NPras