Using C# Generics on Static Classes

I was playing around with some C# generics today and I began thinking about different things I could do with them. Then I began to wonder what happens if you give a static class generic type parameters? I wasn't even sure it would compile but sure enough it did. Then I tried to come up with an example where this might come in handy. Here is a simple factory pattern example using a C# generics:

static void Main(string[] args)
{
    IFactory item = Factory<IFactory, A>.Create(); // Outputs 1
    Console.WriteLine(item.Name);                  // Outputs A
    item = Factory<IFactory, B>.Create();          // Outputs 1
    Console.WriteLine(item.Name);                  // Outputs B
    item = Factory<IFactory, B>.Create();          // Outputs 2
    Console.WriteLine(item.Name);                  // Outputs B
}
public static class Factory<F,T> where T : F, new()
{
    static int count = 0;
    public static F Create()
    {
        count++;
        Console.WriteLine(count);
        return new T();
    }
}
public interface IFactory
{
    string Name { get; }
}
public class A : IFactory
{
    public string Name { get { return "A"; } }
}
public class B : IFactory
{
    public string Name { get { return "B"; } }
}

Now if you take a look at the count variable why is it 1 after I create the first B? Why is it not 2?

The answer is simple once you think about it. For every combination of generic parameters that are used a completely different class is created for that combination. So every combination has its own class thus its own static space, and therefore its own count variable in this example.

This is not a very interesting example but it taught me that generic types can be used by static members as well as static classes. Even deeper you come to realize that for every combination of generic parameters a new class is literally created for each combination.

I hope this will save a few people a couple hours of debugging time. ;)

3 Comments

Comments have been disabled for this content.