Cottleston Pie

Fernando Felman’s thoughts on software development

  • Categories Navigation

  • Topics

  • Archives

  • Advertisements

Recursive Generics Restrictions

Posted by Fernando Felman on September 23, 2007

Here’s an interesting question for you, Generics gurus. Is the following is a valid definition for a generic class in c#?

public class Generic<T> where T : Generic<T>

On first glance it seems that the recursive restriction on type T cannot be possible. For example, if we would like to pass “string” as the type T we would have to wrap it with Generic<string> which in turn needs to be wrapped with Generic<Generic<string>> which in turns needs to be wrapped with Generic<Generic<Generic<string>>> and so on and so forth. But a closer examination reveals that this is actually a valid declaration.

The restrictions on the type T are used to ensure that the type we pass can be treated as the restricted type. In other words, whatever type T we chose to pass, the compiler should be able to cast it to the form Generic<T>. In our case, any class that derives from Generic<T> responds to the restriction and can be used. To conclude, the restrictions on the class Generic<T> defined above ensures that the passed type T is derived from itself (from Generic<T>). For example, the following is a valid class to pass as T:

public class ValidClass : Generic<ValidClass>

 

When can this be used? The recursive restriction shown here can be useful for factories, in which you want to define some basic logic and return a well known type. Consider the following example:

Generic Factory with Recursive Restriction

Using the recursive restriction of Generics we can enforce type affinity to the Employee factory.

Advertisements

3 Responses to “Recursive Generics Restrictions”

  1. C#/C++ developer said

    If you didn’t know, this is called the “Curiously recurring template pattern” and has been used for a long time by C++ developers (although in C# it is severely restricted due to the semantics of generics).

  2. Thanks for the reference 🙂

    I guess this technique is needed when you cannot provide interfaces to the generic implementation class, e.g. when you can’t modify the base implementation of T. I’d still prefer using a well defined interface for the generic class (like IFactory in the factory example shown in the post).

    F

  3. Anon said

    Helped me out, thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

 
%d bloggers like this: