0

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?

Aaginor
  • 4,516
  • 11
  • 51
  • 75
  • 2
    You may use [`ISet`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.iset-1?view=netframework-4.8) or even [`ICollection`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.icollection-1.add?view=netframework-4.8) – Pavel Anikhouski Apr 23 '20 at 12:03
  • complete list of interfaces implemented by `HashSet` https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1 – devio Apr 23 '20 at 12:18
  • I guess you could always use reflection to call `Clear`, after checking it's a `HashSet` using `GetType`. Would that solution satisfy you? Or do you want something cleaner? – Sweeper Apr 23 '20 at 12:23
  • @PavelAnikhouski I believe they are looking for a non-generic interface to use. – juharr Apr 23 '20 at 12:52
  • 1
    Why do you have a method that takes `object` in the first place? Why not something like `public void DoSomething(ICollection o)` instead? That way you protect against someone passing an `int` or a `string` to this method. Also you cannot use `typeOfList` as a generic type in your code but if you make the method generic you can do `GetRandomInstanceOfType` – juharr Apr 23 '20 at 12:59
  • @juharr Because the method SHOULD take objects, I just deal differently with valuetypes, classes and Lists of objects. But to do so, I need to identify them. If it's just values or non-list objects, I can copy the new value to the original value. For lists, I want to clear the original list and add the items of the updated list to the original list – Aaginor Apr 23 '20 at 13:21
  • 1
    @Aaginor That sounds like you should be using overloads. Let the type system determine what you're dealing with instead of relying on reflection. – juharr Apr 23 '20 at 16:37
  • @juharr Might you explain a bit more detailed what you suggest? I know overloads, but I don't see how to use then in this situation, as I cannot overload a HashSet. I guess I'll try to go with the suggestion of Sweeper and use reflection to get the clear and add method for the HashSet. Thanks to all of you for the suggestions! – Aaginor Apr 24 '20 at 07:06

0 Answers0