A delegate in C# is similar to a function pointer in C or 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.
Syntax:
- delegate result-type identifier ([parameters]);
where,
result-type: The result type, which matches the return type of the function.
identifier: The delegate name.
parameters: The Parameters, that the function takes.
An interesting and useful property of a delegate is that it 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.
A sample delegate program:
- using System;
-
- namespace forgetCode
- {
- delegate void Mydel(string s);
-
- class program
- {
- public static void method1(string a)
- {
- Console.WriteLine("Hi," + a);
- }
-
- public static void method2(string b)
- {
- Console.WriteLine("Hello," + b);
- }
-
-
- public static void Main()
- {
-
- Mydel a, b;
-
- a = new Mydel(method1);
- b = new Mydel(method2);
-
-
- a("Forget Code");
- b("Forget Code");
-
- }
- }
- }
Output:
Hi, Forget Code
Hello, Forget Code
..