2

I need to make an interface like this:

public interface ISomething
{
    List<T> ListA { get; set; }
    List<T> ListB { get; set; }
}

And then implement it like this:

public class Something01: ISomething
{
    public List<string> ListA { get; set; }
    public List<Person> ListB { get; set; }
}

Or like this:

public class Something02: ISomething
{
    public List<int> ListA { get; set; }
    public List<string> ListB { get; set; }
}

But looking at other posts it seems like I have to define T in top of my interface class. Which forces me to one specific type for all properties when implementing. Can this be done somehow?

Thanks

henry.dv
  • 187
  • 13
Morten_564834
  • 1,358
  • 3
  • 13
  • 20
  • 1
    You can make the interface generic too: `public interface ISomething`, but you need 2 generic types to do what you want. – DavidG Feb 06 '19 at 09:53

4 Answers4

4

You can make the interface generic, with a type argument for each property that requires a different type, for example:

public interface ISomething<TA, TB>
{
    List<TA> ListA{ get; set; }
    List<TB> ListB {get; set; }
}

And use it like this:

public class Something01: ISomething<string, Person>
{
    public List<string> ListA { get; set; }
    public List<Person> ListB { get; set; }
}
DavidG
  • 104,599
  • 10
  • 205
  • 202
2

"But looking at other posts it seems like I have to define T in top of my interface class. Which forces me to one specific type for all properties when implementing. "

True. But you may define as many generic parameters as you want, not only a single. So in your case this should do it:

public interface ISomething<T, S>
{
    List<T> ListA{ get; set; }
    List<S> ListB {get; set;}
}

Now you can provide two completely independent types:

class MyClass : ISomething<Type1, Type2> { ... }
MakePeaceGreatAgain
  • 33,293
  • 6
  • 51
  • 100
1

You could use

public interface ISomething<T, U>
{
    List<T> ListA{ get; set; }
    List<U> ListB {get; set;}
}

So when you define your class, it'd be

public class Something : ISomething<Person, string>
{
    List<Person> ListA{ get; set; }
    List<string> ListB {get; set;}
}
Szeki
  • 2,584
  • 3
  • 28
  • 41
1

Try this code.

public interface ISomething<T, K>
  {
    List<T> ListA { get; set; }
    List<K> ListB { get; set; }
  }

  public class Something01 : ISomething<string, Person>
  {
    public List<string> ListA { get; set; }
    public List<Person> ListB { get; set; }
  }
Bijay Yadav
  • 876
  • 8
  • 18