Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What use is this code?

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>
{
}
like image 817
RCIX Avatar asked Sep 05 '09 02:09

RCIX


1 Answers

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.

like image 146
dahlbyk Avatar answered Oct 01 '22 02:10

dahlbyk