Search code examples
c#genericsstatic-methodsstatic-classes

How to access all specific versions of a generic static class in C#?


Let's say I have the following static class:

public static class Foo<T>
{
    private static T Baz;

    /* other members */

    public static void Bar()
    {
        //do something with Baz
    }
}

Is there a built-in way to call Bar() for all specific versions of the generic class without knowing the type parameters that were used? That is, if the consumer of Foo<T> has used it as Foo<Larry>, Foo<Curly> and Foo<Moe>, how can I call all the Foo<Larry>.Bar(), Foo<Curly>.Bar() etc. methods automatically without explicitly specifying the generic types?


Solution

  • That is not possible. Use the static constructor of Foo<T> to maintain a global list of Baz values. That global list must be rooted in a static variable that lives outside of Foo<T>.