Ravi Gupta
Ravi Gupta

Reputation: 6480

c#: Extending functionality of an interface keeping it backward compatible

I have an interface called IEvaluator as a part of library I have created.

public interface IEvaluator<T>
{
    public bool Evaluate<T>(T key, T value);
}

Earlier it used to evaluate whether key is equal to value or not. Now, I want to add support for more operators in it say less than, greater than etc keeping it backward compatible at the same time i.e. only those people who want extended support should update their code and not others. I know that .NET provides an similar interface called IComparer<T> but using that is not an option here.

I tried few approached but non of them seems to work

In both the cases, I'm getting that the function with default argument is not implement. What is the correct way of doing such kind of enhancement?

Upvotes: 4

Views: 1751

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503290

You can't, basically. If someone has implemented the original interface, their code doesn't expose any way of using other operators... so you can't expose the extra method without breaking their code.

One option would be to create a new interface which extended the old one:

public interface IFlexibleEvaluator<T> : IEvaluator<T>
{ 
    bool Evaluate<T>(T key, T value, string operatorVal);
}

Then implementations could add support at their leisure. They could perform the "default to equality" part themselves.

Upvotes: 11

Related Questions