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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With