Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Hide a member method by an Extension Method

Tags:

c#

.net

public static class MyClass
{
    public static void Add<T>(this List<T> list, T item)
    {
        list.Add(item);
        Console.WriteLine(item.ToString());
    }
}

then

List<string> list = new List<string>(){"1","2"};
list.Add("3");

But the member method would be called.

Is there anyway to call my Extension Method this way?

I don't want to call it like this:

MyClass.Add(list, item)
like image 965
Jahan Zinedine Avatar asked Jan 11 '11 07:01

Jahan Zinedine


1 Answers

You can't. Instance methods always take precedence over extension methods, assuming they're applicable. Member resolution will only consider extension methods once it's failed to find a non-extension-method option.

I would suggest you simply rename your method - unless the point was to call this method transparently with existing code.

If you made it take an IList<T> instead of List<T>, you could create a wrapper type which implements IList<T> and delegates all calls onto the wrapped list, performing any extra tasks as you go. You could then also write an extension method to IList<T> which created the wrapper - which would allow for more fluent syntax in some cases. Personally I prefer the wrapper approach to deriving a new collection type, as it means you can use it with your existing collections, making the code changes potentially smaller... but it all depends on what you're trying to do.

like image 162
Jon Skeet Avatar answered Oct 10 '22 03:10

Jon Skeet