Introduction
A delegate is an object that can refer to a method. Therefore when you create a delegate, you are creating an object that can hold a reference to a method. The method can be called using this reference. In other words, a delegate can invoke the method and is considered to be a powerful feature.
Advantage
The same delegate can be used to call various methods during runtime of a program by simply changing the method. Therefore, thay is an advantage of a delegate.
Declaration
- A delegate type is declared by the keyword delegate.
- Delegate return-type name (parameter list);
- Where return-type defines the type of value returned by the methods.
Example
- using System;
- namespace ConsoleApplication3
- {
- delegate string delegate_method(string str);
- class delegate_test
- {
- static string Reverse(string s)
- {
- string temp = "";
- int i, j;
- Console.WriteLine("Reversing String...");
- for (j = 0, i = s.Length - 1; i >= 0; i--, j++)
- temp += s[i];
- return temp;
- }
- static void Main(string[] args)
- {
- delegate_method del = new delegate_method(Reverse);
- string str;
- del = new delegate_method(Reverse);
- str = del("neeraj kumar");
- Console.WriteLine("Result is: "+str);
- Console.Read();
- }
- }
- }
Output
The del object is assigned Reverse() then del is called. Then Reverse() is being called.
Delegate method group conversion
A delegate method group conversion defines the simple way of using a delegate. It simplifies the syntax that assigns a method to a delegate. It is called method group conversion.
- static void Main(string[] args)
- {
- delegate_method del = Reverse;
- string str;
- del = new delegate_method(Reverse);
- str = del("neeraj kumar");
- Console.WriteLine("Result is: "+str);
- Console.Read();
- }
Multicasting delegates
Delegates also support an exciting feature called multicasting. Multicasting is the ability to create a chain of methods that will be automatically called when a delegate is invoked and is easy to create. We use the + or the += operator to add methods to the chain and to remove the methods we use – or -=.
Example
- using System;
- namespace ConsoleApplication3
- {
- delegate void delegate_method(ref string str);
- class delegate_test
- {
- static void Reverse(ref string s)
- {
- string temp = "";
- int i, j;
- Console.WriteLine("Reversing String...");
- for (j = 0, i = s.Length - 1; i >= 0; i--, j++)
- temp += s[i];
- s = temp;
- }
- static void Uppercase(ref string s)
- {
- Console.WriteLine("Converting into uppercase...");
- s = s.ToUpper();
-
- }
- static void Main(string[] args)
- {
- delegate_method del;
- delegate_method upper = Uppercase;
- delegate_method reverse = Reverse;
- string str="neeraj kumar";
-
- del = upper;
- del += reverse;
-
- del(ref str);
- Console.WriteLine("Result is: "+str);
- Console.Read();
- }
- }
- }
Output
I hope this article will help you understand delegates.