Search code examples
c#inheritancepolymorphismderived-class

Passing derived class to method when parameter type is base class


This seems to answer my question, but I'm getting an error. It looks like there's a very simple explanation but I can't for the life of me figure out why.

It's the classic polymorphism-inheritance question...
I have a base class

public abstract class Client
{
    public int Start;
    public int End;
}

and two inheriting classes

public class Family : Client { }
public class Helper : Client { }

I insert some values into this list

static List<Family> familySchedule = new List<Family>();

and create a method that takes in Clients

static void SortEarlyToLate(List<Client> clientList)
{
    //some code doing stuff like changing Client.Start
}

Now, when I call

SortEarlyToLate(familySchedule);

I get error

Argument 1: cannot convert from 'System.Collections.Generic.List<ConsoleApp11.Family>' to 'System.Collections.Generic.List<ConsoleApp11.Client>'

According to the question referenced at the top of this question, this should work. The only possibility that I can think of as to why it's not working is that polymorphism doesn't support using an object of the base class inside the method when it's the derived class passed in. Ie using Client.Start inside the method when it's a Family that's been passed in.

If that's correct, isn't there a way to create a generic method that can handle different types?
(Wasn't polymorphism created for exactly this?) Or is the only solution to create the same method twice with different parameters?

If there's a really obvious solution that I've missed, please be nice... I've been grinding my head over this for so long, my brain has completely fuzzed up.

Edit: A more concise summary of my question would be: Although there is a way to allow generic parameters, eg
static void SortEarlyToLate<T>(List<T> clientList) where T : Client,
this prevents the ability to access object properties from inside the method. Now Family.Start will return an error, so will Client.Start. I'm not quite sure what won't return an error. Unless some clever person has an answer, I think currently the only solution is parsing all parameters to Client.


Solution

  • You can see this C# Cannot convert from IEnumerable to IEnumerable

    To bypass this problem, you have 2 choix :

    -Cast your list as list of Client before pass to the method

    SortEarlyToLate(familySchedule.Cast<Client>().ToList());
    

    -Init your list of Client and add Family object.

    static List<Client> clientSchedule = new List<Client>();
    clientSchedule.Add(new Family());