Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Delegates-How do we use them in C#?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 331
    Comment on it

    In the Part-1 we learned about an abstract view of delegates and how we use them. In this article we will see the implementation of delegates which is obviously the basic one but will help you understand that how you will implement that for a UI and any service layer or other data persistence layer scenario.

    What is the most required thing in any application development, making it error free? No, obviously not because you are not letting the user enter garbage values in a textbox or leaving any susceptible scenario unhandled. Apart from that the errors and exceptions are entirely a different issue and can’t be merged with application scalability. What? A new word? Application scalability?

    Yes. Application scalability is something which every client wants and that means that your application can scale to a simple desktop application for a small store or shop to a medium size enterprise application in next 2-4 years of development.  So obviously the classes in which we write all functions must not be tightly coupled which means that for a simple change we need not to recompile the whole code each time. And for this purpose the delegate serves you the best. Let us take a look at about the code part.

    So let us assume that we have a “MathOperations” class which serves as a function store of different basic math operations like addition, subtraction, division and multiplication. The class “MathOperations” looks like following:

    public class MathOperations
    {
       public  int addition(int x , int y)
      {
        return x+y;
      }
    public  int subtraction(int x , int y)
      {
        return x-y;
      }
    public  int multiplication(int x , int y)
      {
        return x*y;
      }
    public  int division(int x , int y)
      {
        return x/y;
      }
    }

    What is the first thing comes to your mind when I say, you can use this class in your application? You might say, just create the object and access the functions and no one in this world can prove you wrong about this. But what if I say that I need it to call in a way that your calling class doesn’t know about this MathOperations class directly and the call is defined by some option supplied by user and also this MathOperations class may add more functionalities but you won’t recompile your UI part (calling class) each time.

    So your answer will be that we need to write this class in a way that it acts as a plug and play assembly.
    That means whenever we want to use the class we can use it from our UI regardless of definition of its functions. We have the options in UI which is supplied by user and whatever value is supplied, the corresponding function is called.

    So we will define a delegate which will point to the methods of the class in abstract manner. Let us see how.

    So in MathOperations class declare a delegate like following:

    public delegate int MathOperationsPointer(int x, int y);

    As you can see , public is the access specifier , delegate is the keyword through which you create a delegate, int is the return type of the delegate and it has a name of “MathOperationsPointer” and it takes two parameters of integer type.

    Now we will point the methods and that’s what a delegate is supposed to do. So let’s take a look at the syntax:

    MathOperationsPointer mathpointer=null;
    mathpointer= addition;

    Our delegate is pointing to the addition method but we need a mechanism for calling methods based on the options supplied from UI section.

    So we can modify our class as following:

    public class MathOperations
    {
    public delegate int MathOperationsPointer(int x, int y);
    public MathOperationsPointer GetMethodbyOption( int methodCode)
    {
      MathOperationsPointer=null;
    Swtich(methodcode)
       {
            case 1:
             MathOperationsPointer=addition;
             break;
            case 2:
             MathOperationsPointer=subtraction;
             break;
            case 3:
             MathOperationsPointer=multiplication;
             break;
             case 4:
             MathOperationsPointer=division;
             break;
            default:
             break;
        }
           return MathOperationsPointer;
    }
    
       int addition(int x , int y)
      {
        return x+y;
      }
    int subtraction(int x , int y)
      {
        return x-y;
      }
    int multiplication(int x , int y)
      {
        return x*y;
      }
    int division(int x , int y)
      {
        return x/y;
      }
    }

    We have done some modification to our method pointing and modified it with a switch case and a method which returns the delegate which is pointing to a method depending on the “methodCode” supplied from user.

    Now we have a class which is having an abstract pointer and we can use this pointer in our UI part or wherever you want like following:

    int  result = mathOperations. GetMethodbyOption (methodCodeFromUI).Invoke(number1,number2);

    What is Invoke here? It invokes the method represented by current instance (mathOperations) using specified parameters (in his case number1 and number2). And what method will be invoked that depends on the switch case in MathOperations class.

    So inside the UI part you can define your conditions and use the above statement like following (say you want to call addition method):

    int  result = mathOperations. GetMethodbyOption (1).Invoke(2,3);

    Here mathOperations is the object of MathOperations class.

    So you will get the result as 5 and depending on the parameters you pass inside “GetMethodbyOption” you may get different results like -1 for subtraction, 6 for multiplication and .6666… for the division method.

    But what was out target behind all this code, addition? No. Our target was to decouple the MathOperations class from the UI (calling) part so that the UI part doesn’t need to be recompiled each time the methods are added or removed from MathOperations class. So we can see that as long as you know that what is the method code for any method inside MathOperations class (you should know that obviously), you don’t need any change in your calling section. Our classes are decoupled. Yay!

    Always remember that this is not the only way to decouple classes, but this is one of the ways. You may say that there are interfaces but again there are scenarios for everything you use. And you can refer to the Part-1 for the same.

    Now the standard and too much compressed version of the answer of “What are delegates” question  looks more relevant. Delegates are definitely pointers to methods. We just confirmed the same in this article.

    Thank You.

     

    Happy Coding. :-)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: