I have two classes where one derives the other. I also have a HashSet field which stores a bunch of Derived classes. The problem is that the Derived class is only used internally and I have a property which needs to return a HashSet of Base classes. I know List has the ConvertAll method, does HashSet have something similar?
public class Base
{
}
public class MyClass
{
private class Derived : Base
{
}
private HashSet<Derived> mList;
public HashSet<Base> GetList { get { /* Convert mList to HashSet<Base> */ } }
}
You cannot convert a
HashSet<Derived>to aHashSet<Base>without casting each item.To explain why this is not possible, have a look at the following code example:
However, since the IEnumerable interface is covariant, the following should be possible:
Thus, you could change your method declaration: