Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension on generic list with specific type?

Is it possible to create an extension method on a generic list with of a specific type for example

List<MyClass> myList = new List<MyClass>();

myList<MyClass>.MyExtensionMethod();

Its important that the MyExtensionMethod only works with a list of type MyClass.

I suspect that this is not possible so what options are there to achieve this?

like image 922
Banshee Avatar asked Dec 19 '14 11:12

Banshee


2 Answers

Ofcourse it is:

public static void MyExtensionMethod(this List<MyClass> m)

It's not clear what you mean by myList<MyClass> but this method will work for all instances of List<MyClass>

like image 62
Selman Genç Avatar answered Oct 04 '22 12:10

Selman Genç


Try this :

 public static class ListExtensions
    {
        public static void ExtensionMethodName<T>(this List<T> list) where T : MyClass
        {
            //Code
        }

        // Or
        public static void ExtensionMethodName(this List<MyClass> list)
        {
            //Code
        }
    }
like image 28
kishan Thakar Avatar answered Oct 04 '22 13:10

kishan Thakar