Delegates - DOTNET

Delegates

Delegates


Before knowing the definition of delegate let’s understand the problem and how delegate solve it.

Problem:   Let’s say we want to do some operations on two numbers. Based on the operation (Add/Sub/Multi/Divide) the out put will vary and for each operation we need to call the corresponding  method from UI layer.
And if we need add new method then there will be code change in the UI layer. So there is tight couplingbetween the UI layer and Business layer.





What problem does delegate solve?
             It reduces the tight coupling between business layer and UI layer (can be any layer)


From the above figure, it is known that delegate can be defined as
Delegate is an abstract pointer or encapsulates method or function. If any new methods added will not effect in the UI layer

For Example:  To understand more, below some sample code is provided. It contains the declaring of delegates, assigning function pointers and invoking it.
Business Layer
public class clsMath
    {
        public delegate int PointerMaths(int x, int y);

        public PointerMaths GetPointer(int intOperation)
        {
            PointerMaths objPointer = null;

            if (intOperation == 1)
            {
                objPointer = Add;
            }
            else if (intOperation == 2)
            {
                objPointer = Sub;
            }
            return objPointer;
        }

        private int Add(int x, int y)
        {
            return x + y;
        }

        private int Sub(int x, int y)
        {
            return x - y;
        }
    }

UI Layer
  clsMath obj = new clsMath();
  int operationValue = 1;//1-Add 2-Sub 
   obj.GetPointer(operationValue).Invoke(10,20);

MultiCast  Deletgate


There will be some cases where we need to call multiple methods of same type. In that case we can use multi cast delegates.
To point multiple methods below is the syntax.

  //Multi function pointing
 objPointer += Add;
  objPointer += Sub; 
 
 objPointer .Invoke(10,20);
 
  // To de allocate from delegate
    objPointer -= Add;
    objPointer -= Sub;

In coming posts, we will provide the information on below points.
1. Events
2. Difference between delegates and Events and when to use.

3. Calling methods asynchronously using delegates
Copyright © 2015 DOTNET All Right Reserved