Somewhere I have read this question. How can we handle situation like this:
I have an interface, In that I have four methods: Add
, Subtract
, Multiply
, Divide
.
I have two classes A and B.
I want A and B to implement this Interface. But I want situation like this:
Add
, Subtract
.Multiply
, Divide
.Please tell me how is this possible in C#? Or by some trick if this is possible please let me know.
The point of an interface is to define a contract between two objects. If you are saying that your object only wants to implement some of the contract, then that breaks the meaning of the interface.
Why don't you use multiple interfaces, one for Add/Subtract and another for Multiply/Divide. Your class can implement any or both of these interfaces.
A class that implements an interface must implement all of its methods. The documentation says:
A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.
It seems to me that what you need is two interfaces:
IAdditiveOperators
which implements addition and subtraction.IMultiplicativeOperators
which implements multiplication and division.Implementing classes can then implement one or other or both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With