I have a class named “baseClass”.
From this class I inherit a class names “inheritedClass” (public class inheritedClass: baseClass)
The baseClass contains a public function that returns a HashSet<baseClass>. When called from the inheritedClass, the return type is obviously still HashSet<baseClass>, but I need a HashSet<inheritedClass>.
A conversion ala (HashSet<inheritedClass>)returnValue, where returnValue is of Type HashSet<baseClass> doesn’t work.
Is there a way to convert the HashSet-Type from baseClass to inheritedClass without converting each element manually?
Thanks in advance,
Frank
Do you really mean C# in the tags?
HashMapis a Java type. Also it generally has two type parameters rather than one…In C#, generic classes are always invariant. Some interfaces will be variant in C# 4, but very few (only those which either only use the type parameter in an output positiion, e.g.
IEnumerable<T>, or only use the type parameter in an input position, e.g.IComparable<T>).If you can provide more precise information about your situation, we’ll probably be able to help come up with a simple solution – particularly if you can use LINQ with its
Cast<T>()method.EDIT: Okay, with
HashSet<T>:Note that even with C# 4 this would be necessary because the compiler doesn’t know that every value in
baseSetis an instance ofDerivedType– there has to be an execution-time check. The reverse (creating aHashSet<BaseType>from aHashSet<DerivedType>) would work in C# 4.FURTHER EDIT: If you just want to use
UnionWith, that doesn’t require aHashSet<DerivedType>– it requires anIEnumerable<DerivedType>. I suggest you do: