When I work with a List of an unknown type, I can use the IList interface like this:
public void DoSomething(object o)
{
if (o is IList oAsList)
{
foreach (object listItem in oAsList)
Console.WriteLine(listItem.ToString());
oAsList.Clear();
Type typeOfList = oAsList.GetType().GetGenericArguments()[0];
oAsList.Add(GetRandomInstanceOfType<typeOfList>());
}
}
This obviously doesn't work for HashSets, as there is nothing like IHashSet. I could cast it to IEnumerable, but then I am missing methods like .Clear() and .Add() which I need, because I want to copy the elements from one HashSet of any type to another HashSet of that type.
How can I do this with HashSets?