Strange C # common symptom

Possible duplicate:
Impossible recursive definition of a generic class?

I just found that

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

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

+7
source share
1 answer

I would not say that it is useless. Let's look at an example below on how to maintain free syntax. In cases when you create some base implementation in Parent and want to provide free declarations ... you can use this restriction in 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 this just an example of how this restriction can be used.

+2
source

All Articles