I keep running into the scenario below over and over again. Currently I get
around not having covariant return types by using an interface and explicit
property definitions which works to some extent, but causes other problems
that occur with explicit definitions and also leads to much more code that
is also more difficult to maintain. The new keyword is not even an option,
if used in the example below Offspring on a Dog when in the context of an
Animal would return null even the Dog class has populated the Dog _offstring
Array. The new keyword is also extremely difficult to debug when the above
null scenario is encountered. As a rule I do not use new, and it is my
opinion that the new keyword should never be used in this context.
My Questions are:
Shouldn't covariant return be part of csharp, I can think of no reason they
would ever cause a problem?
Is the class below a poor design and is there a better way to achieve the
same effect without using covariant return types, and preferably without
interfaces?
How do you overcome the lack of covariant return types?
Thanks,
Mike
public class Animal
{
public virtual Animal[] Offspring
{
get { return this._offspring }
}
private Animal[] _offspring = null;
}
public class Dog : Animal
{
public override Dog[] Offspring
{
get { return this._offspring }
}
private Dog[] _offspring = null;
}