Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a generic class implementing a generic interface with type constraints need to repeat these constraints?

Let's say I have a following C# interface:

public interface IInterface<T> where T : SomeClass
{
    void InterfaceMethod();
}

And SomeClass is defined as follows:

public class SomeClass
{
    public void SomeMethod();
}

Now I'd like to define the implementation of the interface, which won't compile:

public class InterfaceImpl<T> : IInterface<T> 
{
    public void InterfaceMethod()
    {
        T test = default(T);
        test.SomeMethod(); //Gives Error
    }
}

before I change it to:

public class InterfaceImpl<T> : IInterface<T> where T : SomeClass
{
    public void InterfaceMethod()
    {
        T test = default(T);
        test.SomeMethod(); //Compiles fine
    }
}

Wouldn't it make sense that the type constraints are also "inherited" (not the right word, I know) from the interface?

like image 834
Bartek Eborn Avatar asked Feb 05 '15 18:02

Bartek Eborn


Video Answer


1 Answers

The class does not need to repeat these constraints, it needs to supply a type that satisfies the constraints of the interface. There are several ways of doing it:

  • It can supply a specific type that satisfies the constraints, or
  • It can place its own constraints on a generic type that are stronger than what the interface expects, or
  • It can repeat the constraints from the interface.

The key thing is that T in InterfaceImpl<T> belongs to InterfaceImpl, so whatever constraints that are placed on T must be InterfaceImpl's own.

like image 179
Sergey Kalinichenko Avatar answered Oct 23 '22 06:10

Sergey Kalinichenko