C# extension method for generic type class not found by the compiler

Viewed 416

I'm trying to extend a generic type class, but I can't get VS to see the extension methods.

Of course there would be many ways around this and it sure isn't best practice in all situations, but I can't figure out why, of the two apparently identical cases below, the first one works and the other doesn't.

First, an example of a successful attempt to extend the List class (just to prove I can handle the basics):

namespace Sandbox.ExtensionsThatWork
{
    public static class ListExtensions
    {
        public static List<TheType> ExtendedMethod<TheType>(this List<TheType> original)
        {
            return new List<TheType>(original);
        }

    }

    public class ExtensionClient
    {
        public void UseExtensionMethods()
        {
            List<string> a = new List<string>();
            List<string> b = a.ExtendedMethod();
        }
    }

}

However, the object I want to extend is something like this

namespace Sandbox.Factory
{
    public class Factory<T>
    {
        public static Thing<T> Create()
        {
            return new Thing<T>();
        }
    }

    public class Thing<T>{}

    public static class FactoryExtensions
    {
        internal static Thing<FactoryType> CreateFake<FactoryType>(this Factory<FactoryType> original)
        {
            return new FakeThing<FactoryType>();
        }
    }

    public class FakeThing<T> : Thing<T>{}

}

And in this case I can't for the life of me get the compiler to see the extension method.

namespace Sandbox.FactoryClients
{
    public class FactoryClient
    {
        public void UseExtensionMethods()
        {
            Factory.Thing<int> aThing = Factory.Factory<int>.Create();
            ///THE COMPILER WON'T FIND THE CreateFake METHOD
            Factory.Thing<int> aFakeThing = Factory.Factory<int>.CreateFake<int>();
        }
    }
}

What am I missing?

Thank you all for your time.

1 Answers

Your problem has nothing to do with generics.

You're calling the extension as if it were a static method of Factory.Factory<int>, which it cannot be.

C# does not support extension static methods (meaning extension methods that act like static methods of the type of the this parameter) on any type.

You need an instance to call the extension method on (like you do in your "working" example):

using Sandbox.Factory;
        public void UseExtensionMethods()
        {
            Thing<int> aThing = Factory<int>.Create();
            Thing<int> aFakeThing = new Factory<int>().CreateFake();
        }
Related