Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generics question - generic interface constraint

Tags:

c#

generics

Let's say I have some basic interface which is generics-driven:

public interface Inteface<T> {
   void Foo(T t);
}

Now I have some concrete implementation of this interface which is also generic:

public class InterfaceImpl<T> {
   public void Foo(T t) {
      // Whatever
   }
}

This looks OK, but now let's say I have other class:

public class Ololo {
   public void BadFunction<TShouldModelInterface>(TShouldModelInterface shouldModelInterface) {
      // Whatever
   }
}

And let's say I want to perform a check if TShouldModelInterface actually implements any of the possible Interface<T>.

If the interface wasn't generic, I would simply write something like where TShouldModelInterface : Interface.

But is there any way to solve this problem if the interface is a declared as Interface<T>?

like image 879
Yippie-Ki-Yay Avatar asked Dec 10 '10 11:12

Yippie-Ki-Yay


1 Answers

public class Ololo {
   public void BadFunction<TShouldModelInterface, T>(TShouldModelInterface shouldModelInterface)
       where TShouldModelInterface : Interface<T>
   {
      // Whatever
   }
}
like image 58
Tim Robinson Avatar answered Oct 18 '22 18:10

Tim Robinson