C#C
C#4y ago
Kiel

✅ HashSet property with List backing field

Posting here instead of in #database because it's not really related to db-specific stuff.

For reasons described vaguely here: https://github.com/npgsql/efcore.pg/issues/2301, I am looking to implement a HashSet<T> property with a List<T> backing field which updates appropriately as I add and remove objects from the publicly exposed HashSet<T>.
example class:
public sealed class GlobalUser
{
    private List<Snowflake> _blacklistedHighlightUsers = null!;

    public HashSet<Snowflake> BlacklistedHighlightUsers
    {
        get { /* TODO */ }
        set { /* TODO */ }
    }
}

I want the underlying list field to be updated every time I modify the public property. Is there a way to accomplish this without any of the following?
  • never calling Add/Remove/etc methods and instead manually re-assigning the BlacklistedHighlightUsers every time
  • implementing my own wrapper class which overrides the Add/Remove/etc methods to somehow write to this underlying list
  • giving up on doing this in the first place and using a public List<T> and tossing on .ToHashSet().ToList() or .Distinct().ToList() everywhere I go
all are what I'd consider ugly, hacky solutions that I'm not a fan of as they either mean I am overcomplicating things or there really just is not a solution
Was this page helpful?