Cottleston Pie

Fernando Felman’s thoughts on software development

Archive for September, 2007

LINQPad – get your hands dirty with Linq & more on Parallel Processing

Posted by Fernando Felman on September 24, 2007

There’s only one good way to learn new syntax and concepts: get your hands dirty with it. And now we can do just that in Linq using Joseph Albahari’s LINQPad. I especially like the Linq Challenge he posts on that page. Who’s on with me?

More on the Linq topic, Daan Leijen and Judd Hall published a very interesting article regarding PLinq: Running Queries On Multi-Core Processors. On the same issue you will find another great article from those guys: Optimize Managed Code For Multi-Core Machines.

Posted in C# v3, Linq | Leave a Comment »

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.

Posted in Generics | 3 Comments »