Monday 16 November 2015

Delegate in Asp.net

Delegates in ASP.NET

Before going for delegates
We all are familiar with C language. Let us start with C, and look with how function pointers work in C. I think that will be helpful for understanding the concept behind delegates.

Start with a basic function which we will be pointing to:     

int Addition(int input1, int input2)// a function which takes 2 integer parameters as arguments
{
      return input1+input2; // return an integer value
}

Let’s define a pointer to a function which receives 2 integer values.

int (*functionpointer)(int,int);

Now we can simply point to our function:

 functionpointer = &Addition;
Now that we have a pointer to the function, let’s use it:
 int result = (*functionpointer)(2, 3); // result == 5

Passing the pointer to another function is basically the same:
 int Additionnew(int (*functionpointer)(int, int)) {
    return (*functionpointer)(2, 3);
}
I believe the above code will refresh your memory. Now we can move on to delegates.
Ø  Delegates are nothing but they are similar to function pointers in C& C++, unlike C function pointers, delegates are object-oriented, type safe, and secure.

What is Delegate in asp.net?
·         A delegate is a reference type variable that holds the reference to a method. 
·         In asp.net mainly we are using delegates to create custom events for custom controls. And the call-back methods. All delegates are implicitly derived from the System. Delegate class.
·          Delegates are multicast, which means they can simultaneously point to multiple methods. I.e. calling the delegate once will fire off all the attached methods. 

Properties of Delegate

·         Delegates are similar to C, C++   function pointers, but are type safe.
·         Delegates allow methods to be passed as parameters.
·         Delegates can be used to define call-back methods.
·         Delegates can be chained together; for example, multiple methods can be
called on a single event.
·         Methods don't need to match the delegate signature exactly. For more
information, see Covariance and
Contra variance
·         C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately
defined method.

How to declare a Delegate?

Syntax for declaring a delegate is
delegate <return type><delegate name><parameter list>
example : public Delegate int ExampleDelegate(int input)
The above line declares a delegate called “ExampleDelegate” which can dynamically call any method which has a return type of “int” and accepts a single parameter also of type “int”.
Note: The declaration of a delegate type is similar to a method signature. It has a return value and any number of parameters of any type
Example:
There are three steps in defining and using delegates:
·         Declaration
·         Instantiation
·         Invocation
 //Declaring the delegate
using System;

namespace arun.SampleDelegate
{
               public class DelegateExampleClass 
               {
               Public delegate int EvaluateDelegate (int input1, int input2); // Declaration
              
 //Creating methods which will be assigned to delegate object

/*Note: The declaration of a delegate type is similar to a method signature.*/
       Public int FindBig(int input1, int input2)
{
If(input1>input2|| input1==input2)
{
    return input1;           
}
                               else
                              {
                               return input2;

}


public int sum(int input1, int input2)
{
       return input1+input2;
               }
 //Creating the delegate object and assigning methods to those delegate objects
               Public static void Main ()
               {
DelegateExampleClass  DelegateObj = new DelegateExampleClass  ();

//creating delegate objects and
Instantiating to appropriate methods
// methods having the same signature of the delegate

EvaluateDelegate deleobj1 = new EvaluateDelegate (DelegateObj. FindBig);

EvaluateDelegate deleobj2 = new EvaluateDelegate (DelegateObj. sum);
//Calling the methods via delegate objects
Console.WriteLine("Bigger is : " + deleobj1 (25,10 ));
Console.WriteLine("sum of  two inputs: " + deleobj2 (10,5));



}
}


Output:
Bigger is : 25
Sum of  two inputs: 15

Why Delegates?
Let us start with a real life example I think it will be helpful to answer two questions below.
1)      What is delegate?
2)      Why delegate?
Think about a school, in a school there are different entities like Principle, teachers, students etc.
Principle may not be aware about all the students in the school.
As the part of school assessment  principle want to keep a record about each and every students in school  like their personal information, marks, extracurricular activities etc.
Think about the situation where the principle is go to every class and collect the details. And if he do like that how long it will take to collect the information? Think about the complexity. It will take months for collecting the information, assumes if he collect all information manually there will be another problem too! After he collecting all the information from students then somebody change their home (address will change) or somebody attended for an improvement exam and their marks changes then how the principle know about all this? It’s very difficult to handle .how he can overcome this ?, The solution is  he will fix a teacher who controls the class in general sense fix a class teacher for each class. Class teacher have all the information about a class. In this scenario class teacher is the delegate of the class and he has the information about the students. And the students are the methods of the class school. And these methods are assigned with class teachers. When principle want to collect details of the students or want to know about a single student , he simply use the delegate(teacher) and that delegate can call any methods in the class, that means the teacher can call any student in the class he can give all information about the student. Here principle is not aware about each student in the school (methods) but he can call anyone with the help of teacher. And he can get details of any of the student via teacher.

For getting for practical idea we can convert the above scenario into a simple program:


using System;

namespace arun.SchollDelegateExample
{
               public class DelegateSchool 
               {
               Public delegate int SchoolDelegate (int mark1, int mark2,...); // Declaration
                       

                        Public student1(int mark1,int mark2….)
{
           
            // some code that find the performance of the student.
}
Public student 2(int mark1,int mark2….)
{
// some code that find the performance of the student.
}
.
.
.
}


Public static void Main()
{
                        DelegateSchool   schoolobj= new DelegateSchool  ();
                        SchoolDelegate  delegateobj1= new  SchoolDelegate (schoolobj.student1);
                        delegateobj 1(46,32,..); // call the method student1
SchoolDelegate  delegateobj2= new  SchoolDelegate (schoolobj.student1);
                        delegateobj 2(26,38,..); // call the method student2
.
.
}
We are using Delegate many times without knowing we are really using that!

Look, in windows forms there are classes like button, image, textbox etc... All of them have event handlers like button. Click, textbox. Exchange, which are delegates themselves. And when you want to do something on button click you write function which is void and has two augments: of object type and EventArgs. The one who wrote that button class did not know what to do on button click but gave you delegate:

We all are using Event handlers in our program, but the reality is we doesn’t noticed that they are themselves delegates!!!
Example : Consider a simple  button click event
public void butotn_click(object sender, EventArgs e)
{
// some code
}
Since the “button_Click” event handler uses the “EventArgs” class, that is the corresponding event  “button_Click” is using the delegate “EventHandler” which is a .NET Framework defined delegate!! Inside the .NET Framework,
Actually this delegate is defined as follows:

publicdelegatevoid EventHandler(object sender, EventArgs e);


EventArgs” is a .NET Framework class that indicates that there is no special information to be passed to the event handler

Like this we can create our own event handler delegates!


Note :  To create a custom event data class, create a class that derives from the EventArgs class and provide the properties to store the necessary data. The name of your custom event data class should end with EventArgs.





No comments:

Post a Comment