Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I limit class not to implement all the methods of Interface in C#? [closed]

Tags:

c#

interface

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:

  • A can access only Add, Subtract.
  • B can access only Multiply, Divide.

Please tell me how is this possible in C#? Or by some trick if this is possible please let me know.

like image 831
user3729645 Avatar asked Jun 11 '14 10:06

user3729645


2 Answers

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.

like image 191
demoncodemonkey Avatar answered Oct 05 '22 22:10

demoncodemonkey


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.

like image 39
David Heffernan Avatar answered Oct 05 '22 22:10

David Heffernan