Search code examples
c#interfacetraitsdefault-implementation

Default implementation for indexer


What is wrong with my code below or, alternatively, what is the point of a default indexer implementation if it isn't used by default?

public interface IFoo {
    string this[string key] { get => "Default string index getter"; }
}


// Implementor
public class Foo : IFoo {}

// Usage
Foo myFoo = new();
var bar = myFoo["KEY"];

--> Cannot apply indexing to an expression of type 'Baz.Foo'

Solution

  • This is happening because you're referencing it by class, not by the interface.

    It works fine if you use:

    // Usage
    IFoo myFoo = new Foo();
    var bar = myFoo["KEY"];
    

    Why doesn't the class use the interface defaults, by default? Microsoft says:

    That cast from SampleCustomer to ICustomer is necessary. The SampleCustomer class doesn't need to provide an implementation for ComputeLoyaltyDiscount; that's provided by the ICustomer interface. However, the SampleCustomer class doesn't inherit members from its interfaces. That rule hasn't changed. In order to call any method declared and implemented in the interface, the variable must be the type of the interface, ICustomer in this example.

    Source: https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/interface-implementation/default-interface-methods-versions