Search code examples
c#interfacedeclarationencapsulation

C# declare both, class and interface


// interface
public interface IHasLegs { ... }

// base class
public class Animal { ... }

// derived classes of Animal
public class Donkey : Animal, IHasLegs { ... } // with legs
public class Lizard : Animal, IHasLegs { ... } // with legs
public class Snake : Animal { ... } // without legs

// other class with legs
public class Table : IHasLegs { ... }

public class CageWithAnimalsWithLegs {
    public List<??> animalsWithLegs { get; set; }
}

What should I put in the ?? to force objects that inherit from both Animal and IHasLegs? I don't want to see a Snake in that cage neither a Table.

-------------- EDIT --------------

Thank you all for your answers, but here is the thing: What I actually want to do is this:

public interface IClonable { ... }
public class MyTextBox : TextBox, IClonable { ... }
public class MyComboBox : ComboBox, IClonable { ... }

TextBox/ComboBox is of course a Control. Now if I make an abstract class that inherits both Control and IClonable, I will loose the TextBox/ComboBox inheritance that I need. Multiple class inheritance is not allowed, so I have to work with interfaces. Now that I think of it again, I could create another interface that inherits from IClonable:

public interface IClonableControl : IClonable { ... }
public class MyTextBox : TextBox, IClonableControl { ... }
public class MyComboBox : ComboBox, IClonableControl { ... }

and then

List<IClonableControl> clonableControls;

Thank you!!


Solution

  • Why Don't you make a class AnimalwithLegs?

    public abstract class AnimalWithLegs : Animal, IHasLegs{}
    

    then

    public class CageWithAnimalsWithLegs 
    {
       public List<AnimalWithLegs>  AnimalWithLegs { get; set; }
    }