#809 – Extension Method Signatures Shouldn’t Match Class Methods
March 27, 2013 2 Comments
The idea of writing an extension method is to create a method that can be invoked in the same way as one of the instance methods of a class. You can’t override an existing instance method using an extension method, but only add new methods.
If you author an extension method that has the exact same signature as an existing instance method in the class, the compiler won’t complain about your new method. But if you try invoking the method, the original instance method will be called, rather than your extension method.
static class StringExtensions { // Will never get called public static int CompareTo(this string s1, string s2) { return 0; } } class Program { static void Main(string[] args) { string s = "Pan Am"; int n = s.CompareTo("KLM"); // Original CompareTo method called Console.ReadLine(); } }