Delegate
16:02Introduction
In this post I explain about Delegate in C#.
What is Delegate?
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
Why Delegate?
Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs.
How to declare a delegate?
public delegate int PerformCalculation(int x); <Access Modifier> <delegate> <Return Type> <Delegate Name>(<Parameter's>)
How to initialize a delegate?
<Delegate Name> <Delegate Object> = <new> Delegate(<Parameter's>)
Simple Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Anonymous { class Program { public delegate int fun(int Value); public static int del(int Value) { return Value += 7; } static void Main(string[] args) { Program okkk = new Program(); fun obj = new fun(del); Console.WriteLine(obj(50)); Type type = obj.GetType(); Console.WriteLine("\n Base Class for obj Delegate type:\t"+type.BaseType); Console.WriteLine("\n Is Class : \t"+type.IsClass); Console.WriteLine("\n Is Sealed Class : \t"+type.IsSealed); Console.ReadLine(); } } }
Example Delegate Used Method as A Parameter
By default a delegate takes a single instance function or static function as a parameter.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DelegateParam { public delegate void Del(); class delParam { public void fun() { Console.WriteLine("delParam"); } static void Main(string[] args) { delParam c1 = new delParam(); Del obj = new Del(c1.fun); obj.Invoke(); } } }
Type of Delegate
a. Singlecast Delegate
A Singlecast delegate is derived from the System.Delegate class. It can contain a reference for one method at a time. In the above example the delegate uses a Singlecast delegate. It used to invoke a single method. In the given source code example, a delegate CalculateSingleDelegate invokes a method getTotal().
class Program { // Declare a delegate delegate double CalculateSingleDelegate(double p, double t, double r); static CalculateSingleDelegate SI = getTotal; static void Main(string[] args) { double totalInterest; //Method I : Invocation of simple delegate by using Invoke keyword totalInterest = SI.Invoke(120, 1, 3.25); Console.WriteLine("Total Interest of $120 in a year at rate of 3.25% APR is {0}",totalInterest); //Method II : Invocation of simple delegate by passing method name CalculateSingleDelegate D = new CalculateSingleDelegate(getTotal); totalInterest = D(120, 1, 3.25); Console.WriteLine("Total Interest of $120 in a year at rate of 3.25% APR is {0}", totalInterest); Console.ReadKey(); } // Creating methods which will be assigned to delegate object // Gets the total interest. // The Principal. // The Time. // The Rate. //Total Interest static double getTotal(double p, double t, double r) { return (p * t * r) / 100; } }
b. Multicast Delegate
A Multicast delegate is derived from the System.MulticastDelegate class. Multicast delegate can be used to invoke the multiple methods. The delegate instance can do multicasting (adding new method on existing delegate instance) using the + operator and – operator can be used to remove a method from a delegate instance. All methods will invoke in sequence as they are assigned.
In the given source code example, a delegate instance dObjSI invokes the methods getTotal(), getRatePerYear() and getTimeSpan().
// Sample example of multicast delegate class Program { // Declare a delegate delegate double CalculateSimpleInterest(double para1, double para2, double para3); static CalculateSimpleInterest dObjSI = getTotal; static void Main(string[] args) { double SI; //Calculating simple interest SI = dObjSI.Invoke(120, 1, 3.25); //using multicast delegate by invoking method getRatePerYear() dObjSI += new CalculateSimpleInterest(getRatePerYear); double Rate=dObjSI.Invoke(SI, 120, 1); Console.WriteLine("APR rate is {0}", Rate); //using multicast delegate by invoking method getTimeSpan() dObjSI += new CalculateSimpleInterest(getTimeSpan); double TimeSpan = dObjSI.Invoke(SI, 120, 3.25); Console.WriteLine("Time Span is {0}", TimeSpan); Console.ReadKey(); } // Gets the total interest. // The Principal. // The Time. // The Rate. //Total Interest static double getTotal(double p, double t, double r) { return (p * t * r) / 100; } // Gets the interest rate per year. // The Simple Interest. // The Principal. // The Time. // Interest rate per year static double getRatePerYear(double SI, double p, double t) { return (SI * 100)/(p*t); } // Gets the interest time span. // The Simple Interest. // The Principal. // The Rate. // Interest time span static double getTimeSpan(double SI, double p, double r) { return (SI * 100) / (p * r); } }
c. Generic Delegate
Generic Delegate was introduced in .NET 3.5 that don't require to define the delegate instance in order to invoke the methods.
Conclusion
Guys hope I explain it peoperly.
0 comments