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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With