Posted by Fernando Felman on September 24, 2007
Posted in C# v3, Linq | Leave a Comment »
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:
Using the recursive restriction of Generics we can enforce type affinity to the Employee factory.
Posted in Generics | 3 Comments »