C# – When do Extension Methods break

cextension-methodsnet

We are currently discussing whether Extension methods in .NET are bad or not. Or under what circumstances Extension methods can introduce hard to find bugs or in any other way behave unexpectedly.

We came up with:

  • Writing an extension method for types that are not under your control (e.g. extending DirectoryInfo with GetTotalSize(), etc…) is bad, because the owner of the API could introduce a method that hides our extension – and might have different edge cases. For example testing for null in an extension method will automatically translate into a NullReferenceException if the extension method is no longer used due to hiding.

Question:

  • Are there any other dangerous situations than "hiding" that we are not thinking of?

Edit:

Another very dangerous situation.
Suppose you have an extension method:

namespace Example.ExtensionMethods
{
    public static class Extension
    {
        public static int Conflict(this TestMe obj)
        {
            return -1;
        }
    }
}

And use it:

namespace Example.ExtensionMethods.Conflict.Test
{
    [TestFixture]
    public class ConflictExtensionTest
    {
        [Test]
        public void ConflictTest()
        {
            TestMe me = new TestMe();
            int result = me.Conflict();
            Assert.That(result, Is.EqualTo(-1));
        }
    }
}

Notice that the namespace where you use it is longer.

Now you reference a dll with this:

namespace Example.ExtensionMethods.Conflict
{
    public static class ConflictExtension
    {
        public static int Conflict(this TestMe obj)
        {
            return 1;
        }
    }
}

And your Test will fail! It will compile without a compiler error. It will simply fail. Without you even having to specify "using Example.ExtensionMethods.Conflict". The compiler will walk the namespace name and find Example.ExtensionMethods.Conflict.ConflictExtension before Example.ExtensionMethods.Extension and will use that without ever complaining about ambiguous extension methods. Oh the horror!

Best Answer

Some curiosities:

  • extension methods might be called on null instances; this might be confusing (but sometimes useful)
  • the "hiding" issue is a biggie if they have different intent
  • equally, you might get a different extension method with the same name from 2 different namespaces; if you only have one of the two namespaces, this could lead to inconsistent behaviour (depending on which)...
  • ...but if somebody adds a similar (same signature) extension method in a second namespace that your code uses, it will break at compile time (ambiguous)

(edit) And of course, there is the "Nullable<T>/new()" bomb (see here)...