7

As shown in this article, one can define in C#:

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

}

In Delphi, however, the following code does not compile and complains "E2003 Undeclared identifier: 'MyTreeNode<>'":

type
    TMyTreeNode<T: TMyTreeNode<T>> = class
    end;

The formal terminology seems to be "self-referencing generics constraint". I wonder how to do this in Delphi ?

PS:

Another useful article as David pointed out.

Relevent SO post regarding Delphi and covariance / contravariance.

Wikipedia page of co/contra-variance.

1
  • 1
    You just cannot do that with Delphi generic constraints Commented Apr 23, 2014 at 13:37

1 Answer 1

2

There is no way in Delphi to express such a generic constraint. Furthermore, I believe that there is no typesafe way to achieve what can be achieved in C# with such a constraint.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your comment ! Could you help to explain more about "there is no typesafe way to achieve what can be achieved in C# with such a constraint" ?
You are using generics because you want type safety. You can implement the container without type safety by abandoning generics.
Thank you for your comment ! Could you help to show an example regarding "You can implement the container without type safety by abandoning generics." ?
I suppose that you simply remove the constraint and instead add runtime type checking whenever an element is added to the container.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.