Monday 18 December 2017

Delegate And Events In C# With Example

Delegates
 
Delegate is a reference to the method.

Internally a delegate declaration defines a class which is the derived class of System.Delegate or System.MulticastDelegate

 Delegates can call methods synchronously and asynchronously

Once a delegate object has been created, it may dynamically invoke or call the methods at run time

It works like function pointer in C and C++.

It is objected-oriented, secured and type-safe than function pointer.

For static method, delegate encapsulates method only.

For instance method, it encapsulates method and instances both.

Benefit of delegates

 Delegates are object oriented and type-safe and very secure
 Delegate helps in code optimization.

Uses of Delegate

 It is used in events.
 It is used in threading

Types of delegates

1) Singlecast delegates
2) Multiplecast delegates



Three steps in defining and using delegates:

Declaration

To create a delegate, you use the delegate keyword.

[Modifiers] delegate ReturnType delegateName ([parameters]);

 public delegate void DelegateDemo();

The modifier can be public, private, protected, or internal.

The Return Type can be any of the data types and It can also be a type void or the name of a class.


Instantiation

DelegateDemo dd = new DelegateDemo(Display);

Invocation

dd();

Note:

Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match with return types and same parameters otherwise delegate functionality won’t work

Single Cast Delegates

Singlecast delegate holds single method at a time.
They are derived from System.Delegate class.

Example

using System;

public delegate int DelegatDemo(int num1,int num2);

public class LearningPoint92
{

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

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

}

class Program
{
static void Main(string[] args)
{
 LearningPoint92 lp=new LearningPoint92();

DelegatDemo del1 = lp.Add;
Int  i = del1(50, 20);
Console.WriteLine("sum is :"+i);
DelegatDemo del2 = lp.Sub;
Int  j = del2(50, 10);
Console.WriteLine("sub is:"+j);
}
}
Output

sum is :70
sub is:40

Note:
Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.


Multicast Delegates

It holds the reference of more than one method.

Multicast delegates must contain only methods that return type is  void.

Multi cast delegate is used to hold address of multiple methods in single delegate

To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

Example:

using System;
public delegate void MultiDelegateDemo(int num1,int num2);
public class LearningPoint92
{

public static void Add(int x, int y)
{
Console.WriteLine("Addition is: "+(x + y));
}

public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction is: " + (x - y));
}

public static void Mul(int x, int y)
{
Console.WriteLine("Multiplication is: " + (x * y));
}

}

class Program
{
static void Main(string[] args)
{
LearningPoint92 lp=new LearningPoint92(); //Don’t need to  create object because method is static so it is called by classname
MultiDelegateDemo del = LearningPoint92.Add;
del += LearningPoint92.Sub;
del += LearningPoint92.Mul;
del(20, 15);
Console.ReadLine();
}
}

Output

Addition is: 35
Subtraction is: 5
Multiplication is: 300
Anonymous Methods

Anonymous methods are called as nameless methods..
Define an anonymous method with the delegate keyword and a nameless function body
The anonymous method must not have a signature.
The signature and return type is inferred from the delegate type.
For example if the delegate has two parameters and return a double type, then the anonymous method would also have the same signature.
The anonymous methods reduce the complexity of code
Example:
      using System; 
      class LearningPoint92
                { 
 // Delegate Definition 
delegate void Display(); 
static void Main(string[] args) 
 // Delegate instantiation 
  Display obj = delegate 
  { 
 Console.WriteLine("Anonymous User For LearingPoint92"); 
  }; 
  obj(); 
 Console.ReadLine(); 
    } 
    } 
Output:
Anonymous User For LearingPoint92

Events
 Events are notification where action is performed by user.
 Example:
 When you click with mouse – It is mouse click events.
 When you press any key in keyboard – It is Key Press events
Rules
It is created using event keyword.
It has no return type and it is always void.
All events are based on Multicast delegates.

+=operator is used in Events
Syntax:
Accessibility event delegatename eventname; 

Example:
       using System;
     namespace Delegates 
     { 
public delegate void DelegateEventHandler();  //Delegate
       class LearningPoint92
         { 
    public static event DelegateEventHandler add;  //Event
       static void Main(string[] args) 
             { 
                 add += new DelegateEventHandler(Java); 
                 add += new DelegateEventHandler(Dotnet); 
                 add += new DelegateEventHandler(Php); 
                 add.Invoke(); 
                Console.ReadLine(); 
             } 

             static void Java() 
             { 
                 Console.WriteLine("JAVA");   
             } 
       
             static void Dotnet() 
             { 
                 Console.WriteLine("DOTNET"); 
             } 
       
             static void Php() 
             { 
                 Console.WriteLine("PHP"); 
             } 
         } 
     } 
  Output:
           JAVA
           DOTNET
            PHP

No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...