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

hensing1
  • 187
  • 13
Morten_564834
  • 1,479
  • 3
  • 15
  • 26
  • 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
  • 113,891
  • 12
  • 217
  • 223
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
  • 35,491
  • 6
  • 60
  • 111
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;}
}
Peter Szekeli
  • 2,712
  • 3
  • 30
  • 44
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
  • 928
  • 1
  • 9
  • 22