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?
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?
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