Can the interface method with default implementation be implemented implicitly in a class?

98 Views Asked by At

Just the code:

public interface ICalculator
{
    public double Calculate(double x) => x + 5;
}

public class Calculator: ICalculator
{
}

public static class Program
{
    static void Main()
    {
        ICalculator calculator = new Calculator();
        Console.WriteLine("Calculate(2) = {0}", calculator.Calculate(2));
    }
}

It works fine becuse the Calculate method is implemented explicitly. The calculator has the ICalculator type, so everything is ok. But if I'll change the type of the calculator to the Calculator, I'll get error:

        // Was: ICalculator calculator = new Calculator();
        Calculator calculator = new Calculator();
        Console.WriteLine("Calculate(2) = {0}", calculator.Calculate(2));

[CS1061] "Calculator" does not contain a definition for "Calculate" and no accessible extension method "Calculate" accepting a first argument of type "Calculator" could be found (are you missing a using directive of an assembly reference?).

I understand that it's beacuase the Calculate method is implemented explicitly in the class, so

public class Calculator: ICalculator
{
}

really means:

public class Calculator: ICalculator
{
    double ICalculator.Calculate(double x) => x + 5;
}

I'm just wondering if the class can have an implicit implementation of such a method? I couldn't google the answer.

1

There are 1 best solutions below

1
On

In such these scenarios I always use a base abstract class like this:

public interface ICalculator
{
    double Calculate(double x);
}

public abstract class BaseCalculator : ICalculator
{
    public virtual double Calculate(double x) => x + 5;
}

public class Calculator : BaseCalculator { }

And this code will be fine:

Calculator calculator = new Calculator();
Console.WriteLine("Calculate(2) = {0}", calculator.Calculate(2));