In .NET only interfaces and delegate types can be co- and contra-variant. So it is not possible to cast HashSet<SomeType>
to HashSet<object>
.
You want to cast your v
to non-generic version of IEnumerable
interface
dynamic cleanHashSet = Activator.CreateInstance(type);
foreach (object item in (IEnumerable)v)
{
cleanHashSet.Add(Clean(item));
}
If you don't want to use dynamic
keyword then you need to call Add
method with reflection
object cleanHashSet = Activator.CreateInstance(type);
var method = type.GetMethod("Add");
foreach (object item in (IEnumerable)v)
{
method.Invoke(cleanHashSet, new object[] { Clean(item) });
}