- Home /
C# Generics not constraining correctly?
Hi,
I have a problem, I want to use a generic node interface like this:
interface Node<T>
{
int doStuff(T other);
}
I want to make sure that an implementation would always have to be like this:
class Waypoint : Node<Waypoint>
Therefore I declared my node interface like this:
interface Node<T> where T : Node<T>
However, C# seems to ignore it when I use it like this:
class Waypoint : Node<Waypoint>
class WrongClass : Node<Waypoint>
This should not work, since Waypoint is not of type WrongClass? The compiler does not mark it for an error and it does not produce any kind of runtime error when I use
int doStuff(Waypoint other)
in a WrongClass object.
Is there any way to acheive the desired restriction?
greetings
FreetimeCoder
Answer by Jessy · Jun 18, 2013 at 07:14 PM
What you have should indeed compile fine. Waypoint implements Node of Waypoint, and is therefore suitable for use wherever Node of T is required. C# doesn't provide a mechanism to enforce that you use a certain type for generic parameters. You've done the best you can.
Hm ok, I see the error in my reasoning. I'll just have to document how to use this and hope the user does not implment it the wrong way.
Thanks, FreetimeCoder
This is not an answer. Please do not post comments as answers.
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Multiple Cars not working 1 Answer
How to choose base class to make Inherit C# 2 Answers
Distribute terrain in zones 3 Answers
C# inheritance advice 2 Answers