Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Riddle me this: why does the implicit interface implementation error occur?

Consider the following lines of code:

public interface IProduct
{
    string Name { get; set; }
}

public interface IProductList
{
    string Name { get; }

    IProduct GetValueObject();
}

public abstract class BaseProductList<T> : IProductList where T : class, IProduct, new()
{
    public abstract T GetValueObject();

    public string Name { get; set; }
}

This gives me the following warning: Error 1 ConsoleApplication1.EnumTest.BaseProductList-T- does not implement interface member ConsoleApplication1.EnumTest.IProductList.GetValueObject(). ConsoleApplication1.EnumTest.BaseProductList-T-.GetValueObject() cannot implement ConsoleApplication1.EnumTest.IProductList.GetValueObject() because it does not have the matching return type of ConsoleApplication1.EnumTest.IProduct

(Error 1 'ConsoleApplication1.EnumTest.BaseProductList' does not implement interface member 'ConsoleApplication1.EnumTest.IProductList.GetValueObject()'. 'ConsoleApplication1.EnumTest.BaseProductList.GetValueObject()' cannot implement 'ConsoleApplication1.EnumTest.IProductList.GetValueObject()' because it does not have the matching return type of 'ConsoleApplication1.EnumTest.IProduct'. \cencibel\homes$\k.bakker\visual studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\EnumTest\Program.cs 29 23 TestApp)

But when I add this explicit piece of code, it works:

IProduct IProductList.GetValueObject()
{
    return GetValueObject();
}

Why can't .Net figure this one out!?

like image 235
Kees C. Bakker Avatar asked Jun 02 '26 16:06

Kees C. Bakker


1 Answers

A method returning IProduct is not the same as a method returning some-type-implementing-IProduct. You're trying to use covariant return types - which .NET doesn't support.

Basically it's similar to this situation:

// Doesn't compile
class Foo : ICloneable
{
    public Foo Clone()
    {
        return new Foo();
    }
}

Looks good, and allows clients to call Clone() and get back a strongly-typed value - but it doesn't implement the interface. This isn't supported in .NET, and never has been - the generics in your code are just another example of the same problem.

like image 141
Jon Skeet Avatar answered Jun 05 '26 04:06

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!