How Generics Work

One of my fundamental beliefs about programming is that the best programmers understand what’s actually happening under the hood. This is why it is beneficial to look at the code for the .NET framework. Once you understand what’s going on, you have a better understanding of what you can and cannot do. Generics are one of those language features where it helps to understand what’s happening under the hood in order to use the feature to its full potential. To fully understand, we need a bit of a history lesson, so we need to visit our friend C++.

In C++, Generics are called Templated Classes. I think we would have been better off keeping that name since it more accurately represents what is going on.

In C++, Templated Classes are actually handled by the preprocessor, the same thing that resolves the #DEFINE statements and the #INCLUDE statements. What it actually does is create a brand-new class based on the type parameters it is passed.

Once the class has been created by the preprocessor, it is compiled to binary.

While Generics may not actually have the same mechanics (preprocessor, compile) the effect is the same. You are defining a brand-new class when you specify a generic with the type information in the <> parameters.

So, a class defined as:

class GenericText<T>
{
    void foo1(T param1)
    {
    }

    T foo2()
    {
        T v;
        return v;
    }

}

Called using:

var s = new GenericText<string>();

Actually becomes something like:

class GenericTextString
{
    void foo1(string param1)
    {
    }

    string foo2()
    {
        string v;
        return v;
    }

}

and when called like this:

var s = new GenericText<int>();

Becomes this:

class GenericTextInt
{
    void foo1(int param1)
    {
    }

    int foo2()
    {
        int v;
        return v;
    }

}

The name of the class is actually something system-generated, but the class definition is the same as what I’ve represented above.

Since this all happens at compile time, and not at runtime, it would be difficult to use this as a way of generating a class factory. For that, we would need some other syntax, and would need a base class that defined our generic class interface that we wanted to call.

Related Post

2 Responses to “How Generics Work”

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear