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:<
Unfortunately, there isn't a way to fully prevent this, and a generic ICloneable<T>
with no type constraints is enough. Your constraint only limits possible parameters to classes which themselves implement it, which doesn't mean they are the ones currently being implemented.
In other words, if a Cow
implements ICloneable<Cow>
, you will still easily make Sheep
implement ICloneable<Cow>
.
I would simply use ICloneable<T>
without constraints for two reasons:
I seriously doubt you will ever make a mistake of using a wrong type parameter.
Interfaces are meant to be contracts for other parts of code, not to be used to code on autopilot. If a part of a code expects ICloneable<Cow>
and you pass a Sheep
which can do that, it seems perfectly valid from that point.
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:
http://blogs.msdn.com/b/ericlippert/archive/2011/02/03/curiouser-and-curiouser.aspx
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, "IfT
is anX<T>
, thenX<T>
is really anX<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.
http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx