If the type constraint guarantees that T implements IParameter, why cannot I implement IMain's Method with T as an argument?
interface IMain
{
void Method(IParameter parameter);
}
interface IParameter
{
}
class Implementation<T> : IMain where T : IParameter
{
//public void Method(IParameter parameter) { }//accepted implementation
public void Method(T parameter) { }//leaves the class with a "does not implement member..." compiler error
}
CodePudding user response:
If the type constraint guarantees that T implements IParameter, why cannot I implement IMain's Method with T as an argument?
Let's assume for a second that that's legal and see what happens in this scenario.
Suppose, we have two classes that implement IParameter:
class Param1 : IParameter { }
class Param2 : IParameter { }
Then, we create the following object:
var p1 = new Implementation<Param1>();
At this point, p1.Method would only take an argument of type Param1. So, attempting to do something like this won't work:
p1.Method(new Param2()); // This is illegal, as expected.
Now, let's cast p1 to IMain and try again:
var asIMain = (IMain)p1;
asIMain.Method(new Param2()); // What should happen here?!
On one hand, we have IMain whose Method takes an IParameter argument, so it should allow a Param2 object. But on the other hand, the underlying type of asIMain is Implementation<Param1> whose Method only accepts a Param1 argument. The compiler is smart enough to prevent this situation from happening.
