Search code examples
c#winformsmethodsparameter-passing

Passing list of objects to a singular method


As you might know List<String> isn't match List<Object>.

How can I pass objects like:

List<String>
List<Int>
List<className>

to a single method?

For example imagine we have a method like:

public void _AddListOfObject(string TitleOfDaataGridView, List<Object> Values)
{
    _Temp.Columns[0].Name = TitleOfDaataGridView;               
    foreach (object  i in Values)
    {
        //...
    }
}            

Now I'm not able to pass List<string> object to this method.

How can I do that?


Solution

  • Are you looking for generic? Let's use List<T> where T is a generic type:

    // Method has T generic type
    public void _AddListOfObject<T>(string TitleOfDaataGridView, List<T> Values)
    {
        _Temp.Columns[0].Name = TitleOfDaataGridView;  
                 
        // Note, that i is of generic type T now
        foreach (T i in Values)
        {
        ...
        }
    }  
    

    from now on _AddListOfObject accepts list of any type:

    List<int> list1 = new List<int>() { 1, 2, 3 };
    List<string> list2 = new List<string>() { "a", "b", "c" };
    
    _AddListOfObject("TitleInt", list1);
    _AddListOfObject("TitleString", list2);