Decoupling
Delegates also promotes decoupling (It is an Object oriented concept ,I will write about that later). You can learn about Delegates in my article:
For Example you have written a class of Calculator ,in which you have written the methods of addition, Subtraction, Multiplication and Division. Another class is using your these methods. You add some more methods in your class, in order to use these methods you also need to change your class.
Delegates provides solution to this problem .
Lets go through in a example
This is a calculator class which takes inputs and perform Addition,Subtraction,Multiplication and Division operations and return result.
- namespace Delegates
- {
- delegate int Mathoperation(int num1, int num2);
- class Calculator
- {
- public Mathoperation GetOperation(int option)
- {
- Mathoperation mathOperation = null;
- if (option == 1)
- {
- mathOperation = Add;
- }
- else if (option == 2)
- {
- mathOperation = Sub;
- }
- else if (option == 3)
- {
- mathOperation = Div;
- }
- else if (option == 4)
- {
- mathOperation = Mul;
- }
- else
- {
- Console.WriteLine("You choose the wrong option");
- }
- return mathOperation;
- }
-
- private int Add(int num1, int num2)
- {
- return num1 + num2;
- }
- private int Sub(int num1, int num2)
- {
- return num1 - num2;
- }
- private int Div(int num1, int num2)
- {
- return num1 / num2;
- }
- private int Mul(int num1, int num2)
- {
- return num1 * num2;
- }
- }
- }
This is class which is using the above class methods.
- class Program
- {
- static void Main(string[] args)
- {
- This is a class which is using these methods.
- Console.WriteLine("Enter the Option");
- Console.WriteLine("1.Addition");
- Console.WriteLine("2.Subtraction");
- Console.WriteLine("3.Division");
- Console.WriteLine("4.Multiplication");
- int option = int.Parse(Console.ReadLine());
- Calculator Cal_obj = new Calculator();
- int result = Cal_obj.GetOperation(option)
- .Invoke(10, 20);
- Console.WriteLine(result);
- }
- }
Now whatever changes you made in your Calculator class,It would not affect your Program Class which is using the methods of this class.
This is called decoupling .And Object Oriented Method encourages decoupling.