0

I'm new to C# and experimenting with interfaces, coming from the Swift world. I came across default implementations and they look like they could be super powerful.

However I hit a roadblock when I try to implement a method declared in the parent interface concretely (provide a default implementation). And if I ignore the warning and try to define a concrete class(see below), intellisense throws me a error asking me to implement Checkout() method

CSO108: IPhysicalProduct.Checkout(' hides inherited member "Product Checkout(). Use the new keyword if hiding was intended.

Code that replicates the issue.

interface IProduct {

    string name { get; }
    void Checkout();
}

interface IPhysicalProduct : IProduct
{
    void ShipItem() { Debug.Log("Shipping item"); }
    public void Checkout() { ShipItem(); } //CSO108 here
}

interface IDigitalProduct: IProduct
{
    int totalDownloadsLeft { get; }
    void DownloadItem() { Debug.Log($"Downloading item; {totalDownloadsLeft} downloads left"); }
    public void Checkout() { DownloadItem(); } //CSO108 here
}

class PhysicalProd : IPhysicalProduct
{
    public string name => throw new NotImplementedException();

    public void Checkout()
    {
        throw new NotImplementedException();
    }
}

Is it at all possible for the inherited interfaces to define default implementations of the parent's declared methods?

Aswath
  • 1,236
  • 1
  • 14
  • 28
  • `void IProduct.Checkout() { ShipItem(); }` See also https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods#explicit-implementation-in-interfaces – Charlieface Jun 26 '23 at 13:34
  • Yes, that is exactly what I'm looking for. Perhaps my vocabulary prevented me from finding that question. Thank you – Aswath Jun 26 '23 at 13:37
  • 1
    You are almost certainly making `IPhysicalProduct` an abstract base class instead of an interface. Default interface methods have other limitations which you may find difficult to work with here. For example, if you use the code suggested by @Charlieface, you will be forced to use `IPhysicalProduct` everywhere instead of the class (e.g. `IPhysicalProduct prod = new PhysicalProd();`) – DavidG Jun 26 '23 at 13:41
  • @DavidG you are absolutely right. The compiler forces me to cast the concrete class to the interface, which is weird because it already implemented in the interface. But why is there this limitation? – Aswath Jun 27 '23 at 16:28
  • @Aswath See [this answer](https://stackoverflow.com/questions/58950859/default-implementation-in-interface-is-not-seen-by-the-compiler/58950927#58950927) I wrote a while ago – DavidG Jun 27 '23 at 17:14

0 Answers0