Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can extension methods have generic parameters?

Can an extension method have a say: List as one of the parameters?

public static IEnumerable<XElement> GetSequenceDescendants(this IEnumerable<XElement> elements, params List<XName> names)
        {
            //do something
        }

Is there any restriction on the types of parameters an extension method can have?

like image 948
GilliVilla Avatar asked Mar 03 '26 12:03

GilliVilla


1 Answers

The short answer is that an extension method is just a public static method which can be accessed like an instance method of the first parameter (thanks to the this keyword). This means you can use the same parameters you could use in any static method.

But if you want the parameters to actually be generic you'd need to change your method to this:

public static IEnumerable<TElement> GetSequenceDescendants<TElement, TName>(this IEnumerable<TElement> elements, List<TName> names)
{
    //do something
}

You have to specify all the generic arguments in your method definition.

Also, you can't use the params keyword with anything but an array, i.e. params TName[] is okay, but params List<TName> isn't.

like image 195
Bennor McCarthy Avatar answered Mar 06 '26 02:03

Bennor McCarthy