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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With