Home > Software engineering >  C# Overriding interface method from another interface
C# Overriding interface method from another interface

Time:06-20

Let's say I have interface

public interface IRepository
{
    string GetValue();
}

And then I need to extend this interface so it supports cache

public interface ICachedRepository: IRepository
{
    void SetCache(string value);

    string GetValue(bool ignoreCache = false);
}

As you can see, I want to override GetValue method so that it has ignoreCache argument. But it looks like I overload method, instead of overriding it. Is there any way to fully override GetValue, so that class that implements ICachedRepository won't need to implement GetValue from IRepository ?

CodePudding user response:

You can't change the signature when you want to override a method, therefore GetValue(bool) creates an overload, not an override (that the method has a default argument doesn't make a difference). But your ICachedRepository does implement GetValue() as you inherit the base interface.

When you write an implementation for your interface, you have to specify both methods:

public class RepositoryImplementation : ICachedRepository
{
    public string GetValue() {...}
    public string GetValue(bool ignoreCache) { GetValue(false); }
    public void SetCache(string value) {...}
}

The GetValue() method is part of ICachedRepository, even though you don't declare an override in it in ICachedRepository. It's actually illegal to declare overrides in interfaces.

Side note: I would remove the default parameter specification from GetValue(bool ignoreCache = false) because it's confusing when another overload without the parameter exists. Instead, make sure that calling GetValue() and GetValue(false) perform the same operation.

  • Related