Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading