Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# generics interface solution

I have a interface named Man. In this interface I have the method getList() that returns a list of type T (dependent by class that implements the interface). I have 3 classes that implement Man: small, normal, and big. Every class has the method getList() thart returns a list of small or a list of normal or a list of big.

interface Man<T>{
  List<T>getList();
}

class small : Man<small>{
  List<small> getList(){
    return new List<small>(); 
  }
}

class normal : Man<normal>{
  List<normal> getList(){
    return new List<normal>(); 
  }
}

class big : Man<big>{
  List<big> getList(){
    return new List<big>(); 
  }
}

Now I have the class: Home that contains a parameter bed that's an instance of Man. Bed can be of various types: small, normal, big. How can I declare the type parameter for bed?

class Home{
  Man bed<> // what i must insert between '<' and '>'??
}
like image 880
SplitXor Avatar asked Nov 30 '25 04:11

SplitXor


1 Answers

You need to make Home generic, as well:

class Home<T> 
{
    Man<T> bed;

Edit in response to comments:

If you do not know what type of "Man" will exist, another option would be to make your generic class implement a non-generic interface:

public interface IBed { // bed related things here

public class Man<T> : IBed
{
   // Man + Bed related stuff...

class Home
{
     IBed bed; // Use the interface

You can then develop against the shared contract defined by the interface, and allow any type of IBed to be used in the Home.


On an unrelated side note, I'd recommend using better naming schemes here - the names don't make a lot of sense... Why is a "Man" named "bed"? You might also want to review the standard Capitalization Conventions.

like image 179
Reed Copsey Avatar answered Dec 02 '25 17:12

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!