Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing my own Classes to Objects

I have a function WriteList that saves a list into a file. This function has the parameter List<Object> so I can pass different types of Lists as parameter.

    public void WriteList(List<object> input, string ListName)
    {
        WriteToFile("List - " + ListName);
        foreach (object temp in input)
        {
            WriteToFile(temp.ToString());
        }
    }

When calling this function from my code I want to pass the parameter List<Database> where Database is my own made class. I get the following error:

cannot convert from 'System.Collections.Generic.List -Database-' to 'System.Collections.Generic.List-object-'

So my question is how to convert my own class to an Object, and then pass a list to my function.

like image 958
Robin Avatar asked Jan 20 '26 18:01

Robin


1 Answers

List<T> is not covariant. Use IEnumerable<T> instead:

public void WriteList(IEnumerable<object> input, string ListName)
{
    WriteToFile("List - " + ListName);
    foreach (object temp in input)
    {
        WriteToFile(temp.ToString());
    }
}

Or make the method generic:

public void WriteList<T>(List<T> input, string ListName)
{
    WriteToFile("List - " + ListName);
    foreach (T temp in input)
    {
        WriteToFile(temp.ToString());
    }
}

IMO: The second one is better, because there is no boxing/unboxing when used with value types.

like image 191
MarcinJuraszek Avatar answered Jan 23 '26 07:01

MarcinJuraszek