How do I make a method that accepts a list of any type? Doing List<object> gives me the error
Argument 1: cannot convert from ‘System.Collections.Generic.List<VirusThing.Person>’ to ‘System.Collections.Generic.List’ [Virus thing]
What do I need to change to make the following method work with any type of list?
public static void printList(List<object> list)
{
foreach (var item in list)
{
Console.Write(item);
}
}
I saw that Java has something like List<?> that accepts any type of list.
>Solution :
it is better to use generic
public static void printList<T>(IEnumerable<T> list)
{
foreach (var item in list)
{
Console.WriteLine(item.ToString());
}
}
but if you use a complex class, like Person, you will have to override ToString
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return "Person: " + Name + " " + Age;
}
}