Extension methods for both IList and IEnumerable with the same name?

I wrote some extension methods to convert IEnumerable and IList to string. Now that IList inherits from IEnumerable, I have to call them differently.

I'm just wondering if there is a way to avoid this? Can I have an extension method in IEnumerable and then another in IList with the same name and same signature? Kinda, as an override, except that extension methods are, of course, static.

I just would like to use a more efficient method object in the list without having a middle name for the method.

And yes, I know that in this particular case, I must first run the profiler to really see if the second method is better, but I am wondering if you can override extension methods in derived classes at all.

+3
source share
2 answers

Why don't you do what BCL does and try to bring down the same method?

Something like:

public static string Foo<T>(this IEnumerable<T> source)
{
    var list = source as IList<T>;
    if(list != null)
    {
        // use more efficient algorithm and return
    }
    // default to basic algorithm
}

If you absolutely must have two different extension methods with the same name, you can have them in classes in two different namespaces, but this will mean that you can never use them in the same code file, so this is unlikely whether optimally.

+5
source

, , , , . . .

, :

public interface ISecurity
{
    Permissions GetPermissions(Uri resource);
}

public static class SecurityExtensions
{
    public static ISecurity Security(this IPerson person)
    {
       return new SecurityImpl(person);
    }
}

"namespace" .

+4

Source: https://habr.com/ru/post/1727279/


All Articles