Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Method where T is List that implements interface

Tags:

c#

generics

This is similar to C# - Multiple generic types in one list

However, I want a generic method to accept a List of objects that all implement the same interface.

This code gives the error that there is no implicit reference conversion.

public interface ITest { }
public class InterfaceUser : ITest { }
public class TestClass
{
    void genericMethod<T>(T myList) where T : List<ITest> { }
    void testGeneric()
    {
        genericMethod(new List<InterfaceUser>());
    }
}

Can this be done?

like image 682
ShawnFeatherly Avatar asked Jul 12 '11 23:07

ShawnFeatherly


1 Answers

Define T as ITest and take a List<T> as argument

public interface ITest { }
public class InterfaceUser : ITest { }
public class TestClass
{
    void genericMethod<T>(List<T> myList) where T : ITest { }
    void testGeneric()
    {
        this.genericMethod(new List<InterfaceUser>());
    }
}
like image 144
Remo Gloor Avatar answered Sep 25 '22 21:09

Remo Gloor