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()