Introducing of Delegates in C#
In this article I am present step by step Introducing of Delegates in C#. I also explain How to Declaring Delegates C# with code snippet and sample of example
Delegates in C# (C Sharp) permit you to dynamically modification the reference of the ways during a category. A delegate could be a reference sort variable, which holds the relevancy a way. This reference may be modified at runtime, as desired. A delegate is a type-safe object that can point to another method in the application. Delegates are a general purpose mechanism for indirectly calling methods at runtime, their primary use in C# programming for implementing events and the call-back methods. Delegates are two types
Single Cast Delegates
Multi Cast Delegates
Single Cast Delegates: Single cast delegate means which hold address of single method like as explained in above example.
Multicast Delegates: Multicast delegate is used to hold address of multiple methods in single delegate. Multicast Delegates holds multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=
To implement delegates in your application you need to declare delegates and use delegates.
How to Declaring Delegates
The ways that may be documented by a delegate are determined by the delegate declaration. The delegate will check with the ways, that have an equivalent signature as that of the delegate..
The following given syntax is used for delegate declaration:
delegate
Consider the following example ( ExampleDelegate ) of delegate declaration:
public delegate void ExampleDelegate (string s)
Syntax of Delegate & Methods Declaration: Check below sample code for delegate declaration and methods declaration
public delegate int Delegatmethod(int a,int b);
public class Exampleclass
{
public int Addition(int a, int b)
{
return a + b;
}
public int Subtraction(int a, int b)
{
return a - b;
}
}
In this example, the declared delegate type can be used to reference any method. It should have a single parameter of string type and it does not return any value.
Instantiating Delegates
Create the delegate object of the delegate kind, that you have got already created. Assign the address of the specified technique to the delegate object. You'll be victimization this by occupation the builder of the delegate category and spending the strategy name. The subsequent example shows a way to assign the address of a way to a delegate variable:
public void DelegateFunction(string PassValue)
{
//code snippet for Method implementation
}
//Place of Delegate Declaration
public delegate void ExampleDelegate(string ArgValue);
public void UseMethod()
{
//Instantiation of Delegate
ExampleDelegate DelegateObject = new ExampleDelegate(DelegateFunction);
}
In the preceding example, the signature and return type of DelegateFunction matches while the delegate declaration of the ExampleDelegate delegate. The ExampleDelagate delegate can hold the address of DelegateFunction. The address of the DelegateFunction is assigned to the DelegateObject by passing values, the name of the function to the declaring delegate constructor.
Using Delegate
You can decision the delegate by giving the name of the delegate and by passing parameters, if needed. Victimization delegates are comparable to occupation ways. Contemplate a scenario wherever you wish to print info to a file and a screen. There's some common info that has to move to the file and to the screen. There's conjointly some specific info for each. The ways to print the data to the file and screen are completely different. You'll decision these ways at runtime by passing the common data. The following example shows how to use a delegate:
using System;
using System.IO;
namespace DelegateExample
{
public class PrintToDevice
{
static FileStream Filestream1;
static StreamWriter StrWrite;
public delegate void PrintData(string s);
public static void WriteConsole(string str)
{
Console.WriteLine("{0} Console", str);
}
public static void WriteFile(string s)
{
Filestream1 = new FileStream("d:\\Example.txt",
FileMode.Append, FileAccess.Write);
StrWrite = new StreamWriter(Filestream1);
s = s + " File";
StrWrite.WriteLine(s);
StrWrite.file1ush();
StrWrite.Close();
Filestream1.Close();
}
public static void DisplayData(PrintData PMethod)
{
PMethod("This should go to the");
}
static void Main(string[] args)
{
PrintData con1 = new PrintData(WriteConsole);
PrintData file1 = new PrintData(WriteFile);
DisplayData(con1);
DisplayData(file1);
Console.ReadLine();
}
}
}
Hello All,
Delegate is like a buzz word in C#.NET programming. In this article, I explain delegates, multicast delegates and their usage with the help of simple C# programs.
Advantages:
1.Encapsulating the method's call from caller
2.Effective use of delegate improves the performance of application
3.Used to call a method asynchronously
public delegate type_of_delegate delegate_name()
public delegate int mydelegate(int delvar1,int delvar2)
Sample Program using Delegate:
public delegate double Delegate_Prod(int a,int b);
class Class1
{
static double fn_Prodvalues(int val1,int val2)
{
return val1*val2;
}
static void Main(string[] args)
{
//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
Console.Write("Please Enter Values");
int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());
//use a delegate for processing
double res = delObj(v1,v2);
Console.WriteLine ("Result :"+res);
Console.ReadLine();
}
}
Explanation
Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_Prod" is declared with double return type and accepts only two integer parameters.
Inside the class, the method named fn_Prodvalues is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)