11

I can't figure out the use for this code. Of what use is this pattern?

[code repeated here for posterity]

public class Turtle<T> where T : Turtle<T>
{
}
Community
  • 1
  • 1
RCIX
  • 38,647
  • 50
  • 150
  • 207

2 Answers2

9

This pattern essentially allows you to refer to a concrete subclass within the parent class. For example:

public abstract class Turtle<T> where T : Turtle<T>
{
    public abstract T Procreate();
}

public class SeaTurtle : Turtle<SeaTurtle>
{
    public override SeaTurtle Procreate()
    {
        // ...
    }
}

Versus:

public abstract class Turtle
{
    public abstract Turtle Procreate();
}

public class SnappingTurtle : Turtle
{
    public override Turtle Procreate()
    {
        // ...
    }
}

In the former, it's specified that a SeaTurtle's baby will be a SeaTurtle.

dahlbyk
  • 75,175
  • 8
  • 100
  • 122
  • Do you think, this kind of thing would not be required, if there is support for contra variance? – shahkalpesh Sep 05 '09 at 05:20
  • 1
    It's got more uses. It may implement interfaces for the subclass. Like, in Java, `java.lang.Enum` uses the pattern to implement `java.lang.Comparable` for the subclass. I'm sure C# has something similar. – Johannes Schaub - litb Sep 05 '09 at 07:07
  • There are certainly other uses, but they all involve the parent class needing to use the type of its subclass. Regarding implementation of interfaces, you have two choices: implement the interface for T or Turtle. IComparable would only let you compare items of the same subclass, where IComparable> would let you compare any Turtle. And since .NET 4.0's IComparable will be contravariant in T, you will be able to use an IComparable> as an IComparable because T : Turtle. – dahlbyk Sep 05 '09 at 19:40
-1

There is no use that I can see. Basically, it's the same as

public class Turtle
{
}
AngryHacker
  • 59,598
  • 102
  • 325
  • 594