I have two classes (Dog and Cat) which implement a common interface (Mammal). I also have a generic class (Zone) which encapsulates lists of variables of a specific type, and some other functionality.
public interface Mammal{}
public class Cat : Mammal {}
public class Dog : Mammal {}
public class Zone<T> where T : Mammal {}
I want to do something like this:
Zone<Dog> doghouse = new Zone<Dog>();
Zone<Cat> cathouse = new Zone<Cat>();
Zone<Mammal> zoo = new Zone<Mammal>();
Cat meow = new Cat(cathouse); // This cat starts out in the cathouse
cathouse.moveMammalToZone(meow, zoo); // This should move the cat to the zoo
Dog woof = new Dog(zoo); // This dog starts out in the zoo
zoo.moveMammalToZone(woof, cathouse); // This should throw an error/not be possible
Where dogs and cats can both be in a zoo, but only dogs are allowed in the doghouse and only cats in the cathouse. If a dog were to leave the doghouse, he must go to another zone where he is allowed (all dogs and cats must always be in a zone). Therefore, I tried to create a function which moves the animal to a different zone:
public class Zone<T> where T : Mammal {
public bool contains(T mammal){...} // Returns whether the mammal is in this zone
private void remove(T mammal){...} // Removes the mammal from this zone
private void add(T mammal){...} // Adds the mammal to this zone
// NOTE: remove() and add() should never be called unless a mammal is moving
// between zones, otherwise there could be a mammal without a zone, or a mammal with multiple zones
public bool moveMammalToZone<X>(T mammal, Zone<X> zone) where X : Mammal{
// we need to check if the mammal is in this zone, and if it is the right
// type so that it can go to the other zone
if(mammal is X && this.contains(mammal)){
zone.add(mammal as X);
this.remove(mammal);
return true;
}
return false;
}
}
But I'm getting the error: "The type parameter 'X' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint" csharp(CS0413).
The error is on the line
zone.add(mammal as X);
What does this mean? How would I do what I am trying to do?
NOTE: I have found out that changing Mammal to a class instead of interface fixes this problem. Why?