#809 – Extension Method Signatures Shouldn’t Match Class Methods

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();
        }
    }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #809 – Extension Method Signatures Shouldn’t Match Class Methods

  1. Mourad Barakat says:

    Thanks Sean,

    You make a very good point here. It is surprising that the compiler is letting this go without even a warning, which can make developers scratch their head for a while of why the Extension Method is not called?

  2. Pingback: Dew Drop – March 28, 2013 (#1,516) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: