Hello,
First, here's a sample code of what I'm trying to do:
using System.Collections.Generic;
namespace
MyTest{
public interface IZoo
{
List<Animal> Animals { get; set; }
} public class MyHome : IZoo
{
List<Animal> MyDogs = new List<Dog>();
} class Animal
{} class Dog : Animal
{}
}
The code above does not work in C#. It genereates the following error:
Error 1 'MyTest.MyHome' does not implement interface member 'MyTest.IZoo.Animals'
Basically I'm trying to implement an interface that has a property like this:
List<Animal> Animals { get; set; }
But I don't want to implement it exactly as it is, I want to implement it as a more specific list like this:
List<Animal> MyDogs = new List<Dog>();
or like this:
List<Dog> MyDogs = new List<Dog>();
There must be a way to do that... what am I missing?
Thanks,
Nader
NaderPosted Feb 22, 2008, 7:50 AM
That should do it. Thanks for the explanation!
Nader
AlanPosted Feb 22, 2008, 4:45 AM
When a class implements an interface it has to use exactly the same name for each member, and have the same return type, as the interface did.
Consequently, MyHome must implement a property called Animals and MyDogs is therefore regarded as a separate property even though it has the same return type, List, as Animals does.
Another problem with your code is that you can't convert List to List even though Dog is derived from Animal. The generic List classes all derive directly from System.Object and, unlike arrays, are not covariant.
However you are allowed to do this:
Animals.Add(new Dog());
because Dog is implicitly convertible to Animal.
Sinilarly, you can do this:
Animals.AddRange(new Dog[]{new Dog(), new Dog()});
because Dog[] is impicitly convertible to Animal[].