-2

I would like to pass a method a List of a custom type that conforms to an interface. I'd like the method parameter to be a List of the particular interface type.

Is this possible? I can see I can do this if I use an array instead of a List. I've added my code below to help clarify my problem.

public interface TeamMoveCTRL_IF
{
}

public class TeamMember:  TeamMoveCTRL_IF
{
}

public class TeamCTRL
{
    public TeamMember[] team1;
    public List<TeamMember> team2;
    void Start()
    {
        TestArray(team1); //Works
        TestListElement(team2[0]); //Works
        TestList(team2); //Error because team2 is List<TeamMember>
    }

    private void TestList(List<TeamMoveCTRL_IF> team )
    {
    }

    private void TestArray(TeamMoveCTRL_IF[] team)
    {
    }

    private void TestListElement(TeamMoveCTRL_IF member)
    {
    }
}
Jaysmito Mukherjee
  • 1,467
  • 2
  • 10
  • 29
hoboBob
  • 832
  • 1
  • 17
  • 37

3 Answers3

0

You can use this approach:

private void TestList<T>(IEnumerable<T> team)
where T : TeamMember
{
}

Instead of this two implementations:

private void TestList(List<TeamMoveCTRL_IF> team )
{
}

private void TestArray(TeamMoveCTRL_IF[] team)
{
}
PWND
  • 409
  • 3
  • 11
  • 2
    Actually since `IEnumerable` is co-variant just `TestList(IEnumerable team)` would work. You only really need to make it generic if you still pass `List` instead. – juharr Jan 08 '21 at 18:50
  • @juharr, agreed, strange question) – PWND Jan 08 '21 at 18:53
  • why strange? I wanted a method with a parameter type of List. That I can call and pass a List of a type that conforms to that interface. Now I know to use IEnumerable instead. – hoboBob Jan 08 '21 at 19:10
0

It's not allowed. Consider this:

interface I {}
class A : I {}
class B : I {}

void Fn(List<I> lst) =>
    lst.Add(new B());

static void Main() =>
    Fn(new List<A>());

If you were allowed to change the type of the parameter to a list of its interface, you'd be allowed to add anything derived from that interface in the list, whereas the original definition only allows A elements. You'd be breaking the definition of the list.

Blindy
  • 65,249
  • 10
  • 91
  • 131
0

What you trying to do is not correct. There are multiple ways to achieve what you need but it depends on context.

Start from following change and go from there.

    public List<TeamMoveCTRL_IF> team2;
skalinkin
  • 1,024
  • 9
  • 19