Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange C# generic contraint [duplicate]

Possible Duplicate:
Impossible recursive generic class definition?

I just discovered that

public class Foo<T> where T : Foo<T>
{

}

is legal. What exactly does it mean? It seems recursive and is it possible to instantiate something like this?

like image 664
bradgonesurfing Avatar asked Nov 20 '12 09:11

bradgonesurfing


People also ask

Who is Dr Strange based on?

It should come as no surprise, then, that even Strange's likeness in the comics was meant to evoke imagery of one particularly noteworthy horror actor. According to Grunge.com, Vincent Price, the legendary actor known for his long list of horror films, was one of the inspirations for the Sorcerer Supreme.

How did the first Doctor Strange movie end?

After repeatedly killing Strange to no avail, Dormammu finally accepts his bargain, leaving Earth permanently and taking Kaecilius and the zealots with him in exchange for Strange breaking the loop. Disgusted by Strange and the Ancient One defying nature's laws, Mordo renounces his sorcerer career and departs.


1 Answers

I wouldn't say that this is useless. Let's observe the below example how to support fluent syntax. In cases, that you are creating some base implementation in a Parent and would like to provide fluent declarations... you can use this constraint this way

public class Parent<TChild>
    where TChild : Parent<TChild>
{
    public string Code { get; protected set; }

    public TChild SetCode(string code)
    {
        Code = code;
        return this as TChild; // here we go, we profit from a constraint
    }
}

public class Child : Parent<Child>
{
    public string Name { get; protected set; }

    public Child SetName(string name)
    {
        Name = name;
        return this // is Child;
    }
}

[TestClass]
public class TestFluent
{
    [TestMethod]
    public void SetProperties()
    {
        var child = new Child();
        child
            .SetCode("myCode") // now still Child is returned
            .SetName("myName");

        Assert.IsTrue(child.Code.Equals("myCode"));
        Assert.IsTrue(child.Name.Equals("myName"));
    }
}

Please, take it just an example, of how this constraint could be used

like image 86
Radim Köhler Avatar answered Sep 28 '22 06:09

Radim Köhler