Delegates in C#
A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value.
using System;
public delegate void delprt();
class dummy
{
public void prt()
{
System.Console.WriteLine("Eat");
}
public static void Main()
{
dummy obj = new dummy();
delprt delVal = new delprt(obj.prt);
delVal();
}
}
using System;
public delegate void delprt();
class dummy
{
public void prt()
{
System.Console.WriteLine("Eat");
}
public void display()
{
Console.WriteLine("this is the display function");
}
public static void Main()
{
dummy obj = new dummy();
delprt delVal = new delprt(obj.prt);
delVal += new delprt(obj.display);
delVal();
}
}
Example 1: using System;
public delegate void delFunction(int num);
class dummy
{
int val;
void prt(int num)
{
val = num;
System.Console.WriteLine(val);
}
public static void Main()
{
dummy obj= new dummy();
delFunction dd = new delFunction(obj.prt);
dd(44);
}
}
Example 2:
using System;
public delegate void delFunction(int num);
class dummy
{
static int val;
public static void prt(int num)
{
val = num;
System.Console.WriteLine(val);
}
public static void Main()
{
delFunction dd = new delFunction(prt);
dd(44);
}
}
Example 3:
using System;
public delegate int delFunction(int num);
class dummy
{
int val;
int prt(int num)
{
val = num;
return val;
}
public static void Main()
{
dummy obj= new dummy();
delFunction dd = new delFunction(obj.prt);
System.Console.WriteLine(dd(44));
}
}
public delegate double CalculateArea(double val);
public delegate double CalculateVolume(double val);
class Cube
{
static double Area(double val)
{
return (val * val);
}
static double Volume(double val)
{
return (val * val * val);
}
static void Main(string[] args)
{
CalculateArea objArea = new CalculateArea(Area);
CalculateVolume objVol = new CalculateVolume(Volume);
Console.WriteLine("Surface area of Cube: " + objArea(20));
Console.WriteLine("Volume of Cube: " + objVol(20));
}
}
public delegate void Maths (int valOne, int valTwo);
class MathDemo
{
static void Addtion (int valOne, int valTwo)
{
int result= valOne + valTwo;
Console.WriteLine("Addition: " + valOne + " + " + valTwo + " = " + result);
}
static void Subtraction (int valOne, int valTwo)
{
int result = valOne - valTwo;
Console.WriteLine ("Subtraction: "+valOne +" - " +valTwo+ " = " + result);
}
static void Multiplication (int valOne, int valTwo)
{
int result = valOne * valTwo;
Console.WriteLine ("Multiplication: "+valOne +" * " +valTwo+ " = " + result);
}
static void Division (int valOne, int valTwo)
{
int result = valOne / valTwo;
Console.WriteLine ("Division: "+valOne +" / " +valTwo+ " = " + result);
}
static void Main(string [] args) v {
Maths objMaths = new Maths(Addtion);
objMaths += new Maths(Subtraction);
objMaths += new Maths(Multiplication);
objMaths += new Maths(Division);
if (objMaths != null)
{
objMaths(20,10);
}
}
}
using System;
delegate void DelSeries();
class Numbers
{
void Fibonacci()
{
int i = 0, j = 1;
Console.WriteLine("Fibonacci Series of 10 numbers: " + i + " and " + j);
for (int k = 0; k < 10; k++) { int c = i + j; Console.Write(" " + c); i = j; j = c; } Console.WriteLine(); } void Factorial() { int fact = 1; for (int i = 1; i <= 5; i++) { fact *= i; } Console.WriteLine("Factorial of 5: " + fact); } static void Main(string[] args) { Numbers objNum = new Numbers(); DelSeries objSeries = new DelSeries(objNum.Fibonacci); objSeries += new DelSeries(objNum.Factorial); if (objSeries != null) { foreach (Delegate d in objSeries.GetInvocationList()) { try { d.Method.Invoke(objNum, null); } catch (Exception objExcep) { Console.WriteLine("Error: " + objExcep); } } } else { return; } } }
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
public delegate void Messenger(int value);
class CompositeDelegates
{
static void EvenNumbers(int value)
{
Console.Write("Even Numbers: ");
for (int i = 2; i <= value; i += 2) { Console.Write(i + " "); } } void OddNumbers(int value) { Console.WriteLine(); Console.Write("Odd Numbers: "); for (int i = 1; i <= value; i += 2) { Console.Write(i + " "); } } static void Start(int number) { CompositeDelegates objComposite = new CompositeDelegates(); Messenger objDisplayOne = new Messenger(EvenNumbers); Messenger objDisplayTwo = new Messenger(objComposite.OddNumbers); Messenger objDisplayComposite = (Messenger)Delegate.Combine(objDisplayOne, objDisplayTwo); objDisplayComposite(number); Console.WriteLine(); Object obj = objDisplayComposite.Method.ToString(); if (obj != null) { Console.WriteLine("The delegate invokes an instance method: " + obj); } else { Console.WriteLine("The delegate invokes only static methods"); } } static void Main(string[] args) { int value = 0; Console.WriteLine("Enter the values till which you want to display even and odd numbers"); try { value = Convert.ToInt32(Console.ReadLine()); } catch (FormatException objFormat) { Console.WriteLine("Error: " + objFormat); } Start(value); } } }
Covariance and contravariance provide a degree of flexibility when matching method signatures with delegate types.
Covariance permits a method to have a more derived return type than what is defined in the delegate.
Contravariance permits a method with parameter types that are less derived than in the delegate type.
Covariance
using System;
class Shape { }
class Triangle : Shape
{
public delegate Shape Display();
public static Shape ShapeInfo() { }
public static Triangle TriangleInfo() { }
static void Main(string[] args)
{
Display objDispOne = ShapeInfo;
Display objDispTwo = TriangleInfo;
}
}
Contravariance
using System;
class Shape { }
class Triangle : Shape
{
public delegate void Display(Triangle objTriangle);
static Shape ShapeInfo(Shape objShape) { }
static void TriangleInfo(Triangle objTriangle) { }
static void Main(string[] args)
{
Display objDispOne = ShapeInfo;
Display objDispTwo = TriangleInfo;
}
}
using System;
public delegate void Set(int num, string arg);
public delegate void Get();
class Employee
{
string _empName;
int _empID;
void SetDetails(int empNo, string name)
{
_empName = name;
_empID = empNo;
}
void GetDetails()
{
Console.WriteLine("Employee Name: " + _empName);
Console.WriteLine("Employee ID: " + _empID);
}
static void Main(string[] args)
{
Employee objEmp = new Employee();
Set objSet = new Set(objEmp.SetDetails);
Get objGet = new Get(objEmp.GetDetails);
objSet(20, "John");
objGet();
}
}
Steps Required To Implement Delegate
- Defining Delegates
The foremost step is to define the delegate. The definition of the delegate specifies the method signature, return type of the method, access modifier and the delegate name. The method signature specifies the order and type of each argument. The definition of a delegate is indicated by the usage of the delegate keyword. As shown in the above code segment, the delegate name is calculation, it's access modifier is public, it receives two integer arguments and returns an integer value. - Creating Delegate Method Handler(s)
The next step is to define the method(s) that will be associated with the delegate. In the above code segment, a method named add is defined. This method must have same method signature as that of the delegate, as shown in the above code segment. - Hooking up Delegates and Method Handlers
For a delegate method handler to be invoked, it must be assigned to a delegate object. In the above code, the delegate object is calc_delegate and is hooked up to the method handler add. - Invoking the method through the Delegate
The last step is to invoke the methods that are associated with the delegate. A delegate method handler is invoked by making a method call on the delegate itself. This causes the method handler to invoke with the assigned input parameters as if they were invoked directly by the program, as shown in the above code.
Simple Delegate
using System;
public delegate void delprt();
class dummy
{
public void prt()
{
System.Console.WriteLine("Eat");
}
public static void Main()
{
dummy obj = new dummy();
delprt delVal = new delprt(obj.prt);
delVal();
}
}
Delegate Referencing More Than One Methods
using System;
public delegate void delprt();
class dummy
{
public void prt()
{
System.Console.WriteLine("Eat");
}
public void display()
{
Console.WriteLine("this is the display function");
}
public static void Main()
{
dummy obj = new dummy();
delprt delVal = new delprt(obj.prt);
delVal += new delprt(obj.display);
delVal();
}
}
Delegate With Arguments
Example 1: using System;
public delegate void delFunction(int num);
class dummy
{
int val;
void prt(int num)
{
val = num;
System.Console.WriteLine(val);
}
public static void Main()
{
dummy obj= new dummy();
delFunction dd = new delFunction(obj.prt);
dd(44);
}
}
Example 2:
using System;
public delegate void delFunction(int num);
class dummy
{
static int val;
public static void prt(int num)
{
val = num;
System.Console.WriteLine(val);
}
public static void Main()
{
delFunction dd = new delFunction(prt);
dd(44);
}
}
Example 3:
using System;
public delegate int delFunction(int num);
class dummy
{
int val;
int prt(int num)
{
val = num;
return val;
}
public static void Main()
{
dummy obj= new dummy();
delFunction dd = new delFunction(obj.prt);
System.Console.WriteLine(dd(44));
}
}
Multiple Delegates
using System;public delegate double CalculateArea(double val);
public delegate double CalculateVolume(double val);
class Cube
{
static double Area(double val)
{
return (val * val);
}
static double Volume(double val)
{
return (val * val * val);
}
static void Main(string[] args)
{
CalculateArea objArea = new CalculateArea(Area);
CalculateVolume objVol = new CalculateVolume(Volume);
Console.WriteLine("Surface area of Cube: " + objArea(20));
Console.WriteLine("Volume of Cube: " + objVol(20));
}
}
Multicast Delegate
using System;public delegate void Maths (int valOne, int valTwo);
class MathDemo
{
static void Addtion (int valOne, int valTwo)
{
int result= valOne + valTwo;
Console.WriteLine("Addition: " + valOne + " + " + valTwo + " = " + result);
}
static void Subtraction (int valOne, int valTwo)
{
int result = valOne - valTwo;
Console.WriteLine ("Subtraction: "+valOne +" - " +valTwo+ " = " + result);
}
static void Multiplication (int valOne, int valTwo)
{
int result = valOne * valTwo;
Console.WriteLine ("Multiplication: "+valOne +" * " +valTwo+ " = " + result);
}
static void Division (int valOne, int valTwo)
{
int result = valOne / valTwo;
Console.WriteLine ("Division: "+valOne +" / " +valTwo+ " = " + result);
}
static void Main(string [] args) v {
Maths objMaths = new Maths(Addtion);
objMaths += new Maths(Subtraction);
objMaths += new Maths(Multiplication);
objMaths += new Maths(Division);
if (objMaths != null)
{
objMaths(20,10);
}
}
}
Exceptions in Multicast Delegates
using System;
delegate void DelSeries();
class Numbers
{
void Fibonacci()
{
int i = 0, j = 1;
Console.WriteLine("Fibonacci Series of 10 numbers: " + i + " and " + j);
for (int k = 0; k < 10; k++) { int c = i + j; Console.Write(" " + c); i = j; j = c; } Console.WriteLine(); } void Factorial() { int fact = 1; for (int i = 1; i <= 5; i++) { fact *= i; } Console.WriteLine("Factorial of 5: " + fact); } static void Main(string[] args) { Numbers objNum = new Numbers(); DelSeries objSeries = new DelSeries(objNum.Fibonacci); objSeries += new DelSeries(objNum.Factorial); if (objSeries != null) { foreach (Delegate d in objSeries.GetInvocationList()) { try { d.Method.Invoke(objNum, null); } catch (Exception objExcep) { Console.WriteLine("Error: " + objExcep); } } } else { return; } } }
System.Delegate Class
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
public delegate void Messenger(int value);
class CompositeDelegates
{
static void EvenNumbers(int value)
{
Console.Write("Even Numbers: ");
for (int i = 2; i <= value; i += 2) { Console.Write(i + " "); } } void OddNumbers(int value) { Console.WriteLine(); Console.Write("Odd Numbers: "); for (int i = 1; i <= value; i += 2) { Console.Write(i + " "); } } static void Start(int number) { CompositeDelegates objComposite = new CompositeDelegates(); Messenger objDisplayOne = new Messenger(EvenNumbers); Messenger objDisplayTwo = new Messenger(objComposite.OddNumbers); Messenger objDisplayComposite = (Messenger)Delegate.Combine(objDisplayOne, objDisplayTwo); objDisplayComposite(number); Console.WriteLine(); Object obj = objDisplayComposite.Method.ToString(); if (obj != null) { Console.WriteLine("The delegate invokes an instance method: " + obj); } else { Console.WriteLine("The delegate invokes only static methods"); } } static void Main(string[] args) { int value = 0; Console.WriteLine("Enter the values till which you want to display even and odd numbers"); try { value = Convert.ToInt32(Console.ReadLine()); } catch (FormatException objFormat) { Console.WriteLine("Error: " + objFormat); } Start(value); } } }
Covariance and Contravariance in Delegates
Covariance and contravariance provide a degree of flexibility when matching method signatures with delegate types.
Covariance permits a method to have a more derived return type than what is defined in the delegate.
Contravariance permits a method with parameter types that are less derived than in the delegate type.
Covariance
using System;
class Shape { }
class Triangle : Shape
{
public delegate Shape Display();
public static Shape ShapeInfo() { }
public static Triangle TriangleInfo() { }
static void Main(string[] args)
{
Display objDispOne = ShapeInfo;
Display objDispTwo = TriangleInfo;
}
}
Contravariance
using System;
class Shape { }
class Triangle : Shape
{
public delegate void Display(Triangle objTriangle);
static Shape ShapeInfo(Shape objShape) { }
static void TriangleInfo(Triangle objTriangle) { }
static void Main(string[] args)
{
Display objDispOne = ShapeInfo;
Display objDispTwo = TriangleInfo;
}
}
The delegates are used as a reference to the methods
using System;
public delegate void Set(int num, string arg);
public delegate void Get();
class Employee
{
string _empName;
int _empID;
void SetDetails(int empNo, string name)
{
_empName = name;
_empID = empNo;
}
void GetDetails()
{
Console.WriteLine("Employee Name: " + _empName);
Console.WriteLine("Employee ID: " + _empID);
}
static void Main(string[] args)
{
Employee objEmp = new Employee();
Set objSet = new Set(objEmp.SetDetails);
Get objGet = new Get(objEmp.GetDetails);
objSet(20, "John");
objGet();
}
}
No comments:
Post a Comment