Search code examples
c#staticextension-methodsusing

Why can't I call an extension method as a static method when using static import?


Background:

I had a static class, but the static methods weren't extension methods. I decided to refactor the methods into extension methods and didn't expect any code to break since extension methods can be called like static methods. However, code did break when static import was used for the static class holding the extension methods.

Example:

I have a static class with an extension method and a static method:

namespace UsingStaticExtensionTest.Extensions
{
    static class ExtensionClass
    {
        internal static void Test1(this Program pg)
        {
            System.Console.WriteLine("OK");
        }

        internal static void Test2(Program pg)
        {
            System.Console.WriteLine("OK");
        }

    }
}

When I use the following using directive, everything in the test program works fine:

using UsingStaticExtensionTest.Extensions;
namespace UsingStaticExtensionTest

    {
        class Program
        {
            static void Main(string[] args)
            {
                var p = new Program();
                ExtensionClass.Test1(p); // OK
                p.Test1(); // OK
                ExtensionClass.Test2(p); // OK
            }
        }
    }

But when I use the static import using directive to identify just the class with the extension method, I can't call the extension method as a static method:

using static UsingStaticExtensionTest.Extensions.ExtensionClass;
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            //Test1(p); // Error: The name Test1 does not exist in the current context
            p.Test1(); // OK
            Test2(p); // OK **I can still call the static method**
        }
    }
}

Question: Why can't I call an extension method as a static method when using a static import?


Solution

  • Because of language design:

    Using static makes extension methods declared in the specified type available for extension method lookup. However, the names of the extension methods are not imported into scope for unqualified reference in code.

    using Directive