3
Answers

Dynamic validation of generic method implementaions

Jeff

Jeff

16y
2k
1

I have run across this issue plenty of times. I write up this sexy abstract design only to be reminded of this limitation with generics (it's present in Java as well):

interface IData {
    void insert<D>(List<D> list) where D : IData;
}

class Foo : IData {
    void insert(List<Foo> list) {  }
}


the implemented insert SHOULD satisfy the interface insert method (IMO) but it doesn't. I guess the general rule is for the compilers to look for an exact signature rather than a method that fulfills the requirements of the generic method. One cute way to get around this is with:

abstract AData {
    void insert<D>(List<D> list) where D : AData {
        insert(list);
    }
}

class Foo : AData {
    void insert(List<Foo> list) { ...  }
}


This however is a little dangerous, because I have no way to force the implementation of the concrete insert method. You could also cast to Foo in the implementation, but that creates a whole new set of possible complications.

It could be that this somehow doesn't fall with in the scope of generics. And maybe there is a plausable solution elsewhere in the language.. Dunno.

Answers (3)