Thursday, May 7, 2009

C# Puzzle No.14 (advanced)

Suppose we have a generic interface:

   1: public interface IGenericInterface<TValue>
   2: {
   3:    ... interface contract
   4: }

Theoretically this interface can be implemented by any class:



   1: class Foo : IGenericInterface<Bar>
   2: {
   3:   ...
   4: }
   5:  
   6: class Bar : IGenericInterface<Baz>
   7: {
   8:   ...
   9: }

The question is: how do we restrict the interface usage so that the generic parameter can only match the class the interface is implemented on?


Specifically, this should be valid:



   1: class Foo : IGenericInterface<Foo>
   2: {
   3: }

and this should not compile:



   1: class Foo : IGenericInterface<Bar>
   2: {
   3: }
I belive this question has at least few different answers and I wonder which solution would be the most ellegant one.

3 comments:

Deto said...

I was about to give up ..

public interface IGenericInterface<T> where T:IGenericInterface<T> {
}

Must admit this was very good puzzle!

Wiktor Zychla said...

almost.

class Foo : IGenericInterface<Foo>, IGenericInterface<Bar> { }

class Bar :
IGenericInterface<Bar>, IGenericInterface<Foo> { }

would compile.

unfortunately, that's the best solution (which in fact is not a solution) I know.

Deto said...

Hmm, indeed - second class can ruin it up ..

But seems that such restriction is impossible to implement.