Is there any rational reason why the code below is not legal in C#?
class X: IA, IB
{
public X test() // Compliation Error, saying that X is not IB
{
You could use explicit interface implementation to avoid the problem.
class X : IA, IB
{
public X test()
{
return this;
}
IB IA.test()
{
return this;
}
}
interface IA
{
IB test();
}
interface IB
{
}
The signatures must match exactly to what the interface specifies. There's no reason you cannot return an instance of X
from the method, but the method signature will have to use IB
.
As for a rational reason.. it's probably preferable from a code readability point of view.
You could implement the interface explicitly, and provide an alternative signature that returns X
that is not defined by the interface. If you know your IA
is actually an X
, you could use that instead.
Because C# does not support co and contravriance for interfaces in compile time. This way an implementation of IA.Test() method must exactly match its declaration. You can, however, return instance of X in runtime
This can help http://geekswithblogs.net/abhijeetp/archive/2010/01/10/covariance-and-contravariance-in-c-4.0.aspx You can use the "out" keyword
UPDATE: This answer was written in 2009. After two decades of people proposing return type covariance for C#, it looks like it will finally be implemented; I am rather surprised. See the bottom of https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/ for the announcement; I'm sure details will follow.
This feature is called "return type covariance". C# does not support it for the following reasons:
1) The CLR doesn't support it. To make it work in C#, we'd have to just spit a whole bunch of little helper methods that do casts on the return type to the right thing. There's nothing stopping you from doing that yourself.
2) Anders believes that return type covariance is not a good language feature.
3) \We have lots of higher priorities for the language. We have only limited budgets and so we try to only do the best features we can in any given release. Sure, this would be nice, but it's easy enough to do on your own if you want to. Better that we spend the time adding features that improve the developer experience or add more representational power to the language.
public X test();
You must declare a body for all methods in any class that's not abstract.
Try this:
class X : IA, IB
{
public IB test()
{
return new X();
}
}
interface IA
{
IB test();
}
interface IB { };