Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make a method that accepts a list of any type

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading