G
Guest
Hi all,
I'm having trouble with a project that I've distilled down to the following
code. Unfortunately it won't compile and gives the following
error (caused by the call to GetHorses() in HorseFarm's GetAnimals() method):
Cannot implicitly convert type 'MyCollection<Horse>' to
'MyCollection<IAnimal>'
I tried creating an implicit conversion operator in the Horse class but the
compiler informed me that it was illegal to do so when the conversion was to
or from an interface.
I can't quite see why the the conversion doesn't occur automatically as the
Horse class implements IAnimal so you'd think a collection of
horses would be a collection of animals (I can after all return a single
Horse whenever an IAnimal is expected).
That being said, my real implementation is much more complex and I really
need to leverage the equivalent of a GetHorses() method within a HorseFarm's
GetAnimals() method.
Is there some type of design pattern for generics that can solve this?
Thanks,
Dave
--------- CODE START ---------------
public class MyCollection<T>
{
}
public interface IAnimal
{
}
public interface IFarm
{
MyCollection<IAnimal> GetAnimals();
}
public class Horse : IAnimal
{
}
public class HorseFarm : IFarm
{
MyCollection<Horse> horses = new MyCollection<Horse>();
public MyCollection<Horse> GetHorses()
{
return horses;
}
public MyCollection<IAnimal> GetAnimals()
{
return GetHorses();
}
}
--------- CODE END ---------------
I'm having trouble with a project that I've distilled down to the following
code. Unfortunately it won't compile and gives the following
error (caused by the call to GetHorses() in HorseFarm's GetAnimals() method):
Cannot implicitly convert type 'MyCollection<Horse>' to
'MyCollection<IAnimal>'
I tried creating an implicit conversion operator in the Horse class but the
compiler informed me that it was illegal to do so when the conversion was to
or from an interface.
I can't quite see why the the conversion doesn't occur automatically as the
Horse class implements IAnimal so you'd think a collection of
horses would be a collection of animals (I can after all return a single
Horse whenever an IAnimal is expected).
That being said, my real implementation is much more complex and I really
need to leverage the equivalent of a GetHorses() method within a HorseFarm's
GetAnimals() method.
Is there some type of design pattern for generics that can solve this?
Thanks,
Dave
--------- CODE START ---------------
public class MyCollection<T>
{
}
public interface IAnimal
{
}
public interface IFarm
{
MyCollection<IAnimal> GetAnimals();
}
public class Horse : IAnimal
{
}
public class HorseFarm : IFarm
{
MyCollection<Horse> horses = new MyCollection<Horse>();
public MyCollection<Horse> GetHorses()
{
return horses;
}
public MyCollection<IAnimal> GetAnimals()
{
return GetHorses();
}
}
--------- CODE END ---------------