Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflexive type parameter constraints: X<T> where T : X<T> ‒ any simpler alternatives?

Every so often I am making a simple interface more complicated by adding a self-referencing ("reflexive") type parameter constraint to it. For example, I might turn this:

interface ICloneable
{
    ICloneable Clone();
}

class Sheep : ICloneable
{
    ICloneable Clone() { … }
} //^^^^^^^^^^

Sheep dolly = new Sheep().Clone() as Sheep;
                                //^^^^^^^^

into:

interface ICloneable<TImpl> where TImpl : ICloneable<TImpl>
{
    TImpl Clone();
}

class Sheep : ICloneable<Sheep>
{
    Sheep Clone() { … }
} //^^^^^

Sheep dolly = new Sheep().Clone();

Main advantage: An implementing type (such as Sheep) can now refer to itself instead of its base type, reducing the need for type-casting (as demonstrated by the last line of code).

While this is very nice, I've also noticed that these type parameter constraints are not intuitive and have the tendency to become really difficult to comprehend in more complex scenarios.*)

Question: Does anyone know of another C# code pattern that achieves the same effect or something similar, but in an easier-to-grasp fashion?


*) This code pattern can be unintuitive and hard to understand e.g. in these ways:

  • The declaration X<T> where T : X<T> appears to be recursive, and one might wonder why the compiler doesn't get stuck in an infinite loop, reasoning, "If T is an X<T>, then X<T> is really an X<X<…<T>…>>." (But constraints obviously don't get resolved like that.)

  • For implementers, it might not be obvious what type should be specified in place of TImpl. (The constraint will eventually take care of that.)

  • Once you add more type parameters and subtyping relationships between various generic interfaces to the mix, things get unmanageable fairly quickly.

like image 954
stakx - no longer contributing Avatar asked Jan 14 '12 22:01

stakx - no longer contributing


People also ask

Which keyword is used to apply constraints on type parameter?

By using where keyword, we can apply constraints on generics. In c#, you can apply multiple constraints on generic classes or methods based on your requirements. In c#, you have a different type of constraints available; those are class, structure, unmanaged, new(), etc.

Which of the following constraint specifies that any type argument in a generic class declaration must have a public parameter less constructor?

The new constraint specifies that a type argument in a generic class or method declaration must have a public parameterless constructor.

What is type parameter in C#?

In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type.


1 Answers

Main advantage: An implementing type can now refer to itself instead of its base type, reducing the need for type-casting

Though it might seem like by the type constraint referring to itself it forces the implementing type to do the same, that's actually not what it does. People use this pattern to try to express patterns of the form "an override of this method must return the type of the overriding class", but that's not actually the constraint expressed or enforced by the type system. I give an example here:

https://ericlippert.com/2011/02/02/curiouser-and-curiouser/

While this is very nice, I've also noticed that these type parameter constraints are not intuitive and have the tendency to become really difficult to comprehend in more complex scenarios

Yep. I try to avoid this pattern. It's hard to reason about.

Does anyone know of another C# code pattern that achieves the same effect or something similar, but in an easier-to-grasp fashion?

Not in C#, no. You might consider looking at the Haskell type system if this sort of thing interests you; Haskell's "higher types" can represent those sorts of type patterns.

The declaration X<T> where T : X<T> appears to be recursive, and one might wonder why the compiler doesn't get stuck in an infinite loop, reasoning, "If T is an X<T>, then X<T> is really an X<X<…<T>…>>."

The compiler does not ever get into infinite loops when reasoning about such simple relationships. However, nominal subtyping of generic types with contravariance is in general undeciable. There are ways to force the compiler into infinite regresses, and the C# compiler does not detect these and prevent them before embarking on the infinite journey. (Yet. I am hoping to add detection for this in the Roslyn compiler but we'll see.)

See my article on the subject if this interests you. You'll want to read the linked-to paper as well.

https://ericlippert.com/2008/05/07/covariance-and-contravariance-part-11-to-infinity-but-not-beyond/

like image 53
Eric Lippert Avatar answered Oct 09 '22 14:10

Eric Lippert