Delegates in C# Notes
Delegates in C# Notes
As written in MSDN
1. Type safe
2. Object Oriented
3. Secure
1. Delegates are similar to C++ function pointer but it is type safe in nature.
2. Delegate allows method to pass as an argument.
3. Delegate can be chained together.
4. Multiple methods can be called on a single event.
Delegate is a type which safely encapsulates a method. The type of the delegate is
defined by name of the delegate. A delegate does not care about class of the object
that it references. Any object will do, only matter is that the method signature
should be the same as of delegate.
Any instance of a given delegate can refer to any instance or static method on any
object of any type. Only one condition is there that signature of method matches
the signature of delegate.
Mainly Delegate is used by creating first and then making object of that.
Main Advantage Delegate is effective use of delegate increase performance of
application.
Syntax of a delegate
Step 1: Declaration
Step 2: Instantiation
Step 3: Invocation
Delg_object_name([parameter....]);
Delegate Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelgateForNotes
{
class Program
{
// Declaring A delegate , which will refer function having
two parameter and will return integer
public delegate int AddDelegate(int num1, int num2);
static void Main(string[] args)
{
// Creating method of delegate, and passing Function
Add as argument.
AddDelegate funct1= new AddDelegate(Add);
// Invoking Delegate.....
int k=funct1(7,2);
Console.WriteLine(" Sumation = {0}",k);
Console.Read();
}
// Static Function Add, which having same signature as of
delegate
public static int Add(int num1, int num2)
{
Console.WriteLine("I am called by Delegate");
int sumation;
sumation= num1+ num2;
return sumation;
}
}
}
Output:
I am called by Delegate
Sumation =9
Purpose of this above code is to calculate a sum of two numbers. Add is a static
function to compute sum of two integers. Signature of Add function is same as of
signature of delegate. Here delegate is AddDelegate.
Step 1:
Creating Delegate.
Step 2:
Step 3:
Invoking delegate
int k=funct1(7,2);
Delegate Example 2
This is bubble sort example. Here three classes have been created.
1. BubbleSortClass.cs
2. Student.cs
3. Program.cs
BubbleSortClass.cs
This class will hold a static function called Sort. The return type of this function is
void. As an argument, it is taking an Array, which is to be sort and a method
which is comparing two objects.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelgateForNotes
{
public class BubbleSortClass
{
Student.cs
The object of this class is going to be sort using the Bubble sort. In this class, the
static function RhsIsGreater is performing the function of comparing two Student
objects.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelgateForNotes
{
// Student class
class Student
{
private string name;
private int rollno;
private int marks;
// Constructor to initaliaze object
public Student(string name, int rollno, int marks)
{
this.name = name;
this.rollno = rollno;
this.marks = marks;
The RhsIsGreater function is taking two object as argument. Inside function, first
typecasting has been done. Then boolean value is getting returned.
Program.cs
This is main program. Here delegate is getting created and sorted array is getting
display.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelgateForNotes
{
public class Program
{
// Declaring A delegate , which will refer function having
two object parameter and will return boolean value
MultiCast Delegates
A delegate which wrap up more than one method is called Multicast Delegates.
When a multicast delegate is get called, it will successively call each functions in
order. Multicast Delegate allow to chain together several functions. These chain
functions can be called together when delegate is invoked. Every Delegate type
has a built in support for dealing with multiiple handlers. Delegate gets this
support by inheriting from the MultiCastDelegate class.
Delegate classes
System.Delegate
The purpose of a single delegate instance is very similar to a method pointer from
C++. However, in C# don't use method pointers, rather, it save the "metadata"
that identifies the target method to call. System.Delegate contains two critical data
elements. Firstly, it contains an instance of System.Reflection.MethodInfo – in
other words, the .NET metadata that enables method invocation using reflection.
The second aspect of System.Delegate is the object instance on which the method
needs to be invoked. Given an unlimited number of objects that could support a
method that matches the MethodInfo signature, we also need to be able to identify
which objects to notify. The only exception is when the method identified by
MethodInfo is static – in which case the object reference stored by
System.Delegate is null.
System.MulticastDelegate
Sequential Invocation
When invoking the multicast delegate, each delegate instance in the linked list is
called sequentially. This sequential invocation, however, leads to problems if the
invoked method throws an exception or if the delegate itself returns data.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MulticastDelegate1
{
class Program
{
// Decelaring delegate here, which will refer to method
having void return type and one string as argument
public delegate void showDelegate(string s);
static void Main(string[] args)
{
showDelegate s = Display;
s += Show;
s("Hello");
s("Scott");
Console.Read();
}
}
}
OUTPUT:
Hello
Hello
Scott
Scott
In the above example, the showDelegate is a delegate, which can refer any method
having return type void and one string as parameter. There are two static user
defined functions called Display and Show.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MulticastDelegate
{
// user defined class for math operation. This class contains
two static method. one method for squre and another method for
double the number.
class MathOperation
{
// Multiply by two method, this method multiply number by
2
public static void MultiplyByTwo(double d)
{
double res = d*2;
Console.WriteLine("Multiply: "+res.ToString());
}
// squre number method
public static void Squre(double e)
{
double res = e * e;
Console.WriteLine("Square"+res.ToString());
}
}
class NewProgram
{
// Decelaring delegate called del
public delegate void del(double Qr);
static void Main()
{
// Creating delegate
del d = MathOperation.MultiplyByTwo;
// adding method to del delegate using += operator
d += MathOperation.Squre;
// calling display function. passsing delegate and double
value as parameter
Display(d, 2.00);
Display(d, 9.9);
Console.ReadLine();
}
This is delegate decelaration. It will refer method having one double parameter and
will return void.
Let's say we have a class with two methods that have the same signature (same
return type and same parameter configuration).
We can point to either of the methods in our class by using a delegate declared as
follows:
Now, if we have another class and want to execute either of the methods in
MyObject, we can do it through the delegate as in the "Do()" method in the class
below. As a matter of fact, we can pass any method with the same signature (not
JUST the methods in MyObject). Check out the MySecondObject.Subtract()
method.
public MySecondObject()
{
a=4;
b=5;
obj = new MyObject();
}
switch(pMethod)
{
case"Add":
del = new MyMethodDelegate(obj.Add);
break;
case"Multiply":
del = new MyMethodDelegate(obj.Multiply);
break;
case "Subtract":
del = new MyMethodDelegate(this.Subtract);
break;
}
return del(a,b);
}
Hopefully this gives you a better idea of what delegates are and how they are
implemented.
Happy coding,
C# .Net Delegates and Events
Need of delegate
Example:
Delegate magic
Delegate does not know or care about the class of the object that
it references. Any object will do; all that matters is that the
method's argument types and return type match the delegate's.
This makes delegates perfectly suited for "anonymous"
invocation.
Benefit of delegates
Types of delegates
1) Singlecast delegates
2) Multiplecast delegates
Multicast Delegate
In C#, delegates are multicast, which means that they can point
to more than one function at a time. They are derived from
System.MulticastDelegate class.
1. Declaration
2. Instantiation
3. Invocation
d1();
using System;
namespace ConsoleApplication5
{
class Program
{
public delegate void delmethod();
public class P
{
public static void display()
{
Console.WriteLine("Hello!");
}
}
static void Main(string[] args)
{
// here we have assigned static method
show() of class P to delegate delmethod()
delmethod del1 = P.show;
del1();
del2();
del3();
Console.ReadLine();
}
}
}
Program to demonstrate Multicast delegate
using System;
namespace delegate_Example4
{
class Program
{
public delegate void delmethod(int x, int y);
Console.WriteLine();
//Here again we have multicast
del -= new delmethod(obj.plus_Method1);
//Only subtract_Method2 is called
del(20, 10);
Console.ReadLine();
}
}
}
An Anonymous Delegate
using System;
Display();
return 0;
}
}
Events
Example:
using System;
namespace delegate_custom
{
class Program
{
public delegate void MyDelegate(int a);
public class XX
{
public event MyDelegate MyEvent;
obj.RaiseEvent();
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace delegate_custom_multicast
{
class Program
{
public delegate void MyDelegate(int a, int b);
public class XX
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace delegate_anonymous
{
public partial class Form1 : Form
{
public delegate int MyDelegate(int a, int b);
public Form1()
{
InitializeComponent();
}
Output
Conclusion
Events in C#
Delegates are used as the means of wiring up the event when the
message is received by the application.
Event Receiver
1. An application
2. An Object
3. A component
Event Sender
1. An assembly in an application
2. An object
3. System events like Mouse event or keyboard entry.
Example:
Example 1:
using
System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace EventExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Adding EventHandler to Click event of Buttons
btn1.Click +=new EventHandler(Button_Click);
btn2.Click +=new EventHandler(Button_Click);
}
}
}
In above code
Output:
When button Scott is clicked, in message Box Scott is
displaying. In this case Button_Click method is called by
btn1_click delegate. In Button_Click() method , checking has
been done for which Button object is calling the event. Or in other
words which button is event sender. Code snippet which is
checking the sender is
if
(sender == btn1)
{
str = btn1.Text;
MessageBox.Show(str+" Clicked ");
}
if (sender == btn2)
{
str = btn2.Text;
MessageBox.Show(str+ " Clicked ");
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace EventExampleTime
{
#region infoOfEvent
public class TimeEvent : EventArgs
{
public readonly int Hour;
public readonly int Minute;
public readonly int Second;
#endregion
#region observerClass
public class DisplayClock
{
public void Subscribe(Clock theClock)
{
theClock.SecondChanged += new
Clock.SecondChangeHandlerDelegate(timeHasChanged);
}
public void timeHasChanged(object theClock, TimeEvent ti)
{
Console.WriteLine("Current Time : {0}:{1}:{2}",
ti.Hour.ToString(), ti.Minute.ToString(), ti.Second.ToString());
}
}
#endregion
#region observerClass2
public class LogCurrentTime
{
public void Subscribe(Clock theClock)
{
theClock.SecondChanged += new
Clock.SecondChangeHandlerDelegate(writelogentry);
}
public void writelogentry(object theClock, TimeEvent ti)
{
Console.WriteLine(" Logging to File : {0}:{1}:{2}",
ti.Hour.ToString(), ti.Minute.ToString(), ti.Second.ToString());
}
}
#endregion
class Program
{
static void Main(string[] args)
{
Clock theClock = new Clock();
DisplayClock dc = new DisplayClock();
dc.Subscribe(theClock);
LogCurrentTime lct = new LogCurrentTime();
lct.Subscribe(theClock);
theClock.Run();
Console.Read();
}
}
}