jack jack - 3 months ago 10
C# Question

Generic function for two List<>

I have two List<> with the same field that I need to edit. How to write a common function for these lists?

public List<?> CutField(List<?> list)
{
foreach(var element in list)
{
element.Field = // ;
}
return List<?>;
}

Answer

Best way would be using generics:

public List<T> CutField<T>(List<T> list) where T : MyInterface
{
    foreach(T element in list)
    {
        element.Field = // ;
    }

    return list;
}

With

public interface MyInterface 
{ 
    object Field { get; set; } // or whatever datatype you need for the field
}

Of course all the possible types within your list should implement that interface.

As an aside you can also omit the return-type from CutField, as you´re already modifying the list passed as parameter.