Home > Software design >  Passing A Generic List
Passing A Generic List

Time:06-02

I am trying to pass a generic list to a function.

Code now works thanks to Mong Zhu.

Full code:

public static bool FillDropDownBox<T>(ComboBox box, List<T> list, string displayMember, string valueMember) where T:class
{ 
        if (list.Count > 0)
        {
            box.Items.Clear();
            box.Items.AddRange(list.ToArray());                
            box.DisplayMember = displayMember;
            box.ValueMember = valueMember;
            return true;
        }
        else
        {
            Debug("List is empty");
            return false;
        }            
    }

    public static List<Client> ClientList = new List<Client>();


    public static void FillClientBox(ComboBox box, Control control)
    {
        if(FillDropDownBox(box, ClientList, "Nickname", "Id")){

    }
 }


CodePudding user response:

In your method:

public static bool FillDropDownBox<T>(ComboBox box, List<T> list, string displayMember, string valueMember) where T:List<T> 

T specifies the type of object that populates the List and you restrict it to be a list of lists!

So when you call it you specify it as the entire list, but you pass only a normal list which I assume is a List<Client>:

FillDropDownBox<List<Client>>(box, ClientList, "Nickname", "Id")

so the compiler expects a list of lists! that is your problem.

change the restriction to where T:class

Actually you should be able to remove the explicit declaration at all and the compiler can infer the type from the passed list ClientList

public static void FillClientBox(ComboBox box, Control control)
{
    if(FillDropDownBox(box, ClientList, "Nickname", "Id")){
}

CodePudding user response:

You just need to do this:

public static bool FillDropDownBox<T>(ComboBox box, List<T> list, string displayMember, string valueMember)
{
    if (list.Count > 0)
    {
        box.Items.Clear();
        box.Items.AddRange(list.ToArray());
        box.DisplayMember = displayMember;
        box.ValueMember = valueMember;
        return true;
    }
    else
    {
        Debug("List is empty");
        return false;
    }
}

public static void FillClientBox(ComboBox box, Control control)
{
    if (FillDropDownBox<Client>(box, ClientList, "Nickname", "Id"))
    {
    }
}

Because the parameter is a List<T> you do not need to constrain T.

And when you call FillDropDownBox you just need to specify the type - if you specify it as List<Client> then you're saying that the list parameter is List<List<Client>>.

CodePudding user response:

In your FillDropDownBox<List<Client>> method you must have a parameter like this:

List<T> listOfClients,

so you have to write it to:

T listOfClients,
  • Related