delegate
In this chapter you will learn:
Get to know delegate
A delegate is a type for method. The method referenced by delegate can be called through the delegate. A delegate in C# is similar to a function pointer in C/C++. The same delegate can call different methods.
A delegate is declared using the keyword delegate. The general form of a delegate declaration:
delegate ret-type name(parameter-list);
ret-type
is return type.- The parameters required by the methods are specified in the
parameter-list
.
A delegate can call only methods whose return type and parameter list match those specified by the delegate's declaration.
All delegates are classes that are implicitly derived from System.Delegate.
Create delegate
The following code defines a delegate.
delegate void Printer(int i);
Here the Printer is the name of the delegate. It is like the name of the class or a struct. Later we can use it as a type.
using System;/*from jav a 2s .c o m*/
delegate void Printer(int i);
class Test
{
static void consolePrinter(int i)
{
Console.WriteLine(i);
}
static void Main()
{
Printer p = consolePrinter;
p(33);
}
}
The output:
In the code above we define a variable p
whose type is Printer
.
delegate defines a way we should follow to create methods.
Then later we can use the delegate type to reference the methods with the same form.
Printer
delegate requires that the type of method should
take single int
type as input and return void
.
instance delegate method reference
To add instance method from a type(class) we have to reference the instance type name.
using System;//from jav a 2 s . c om
delegate void Printer(int i);
class MyClass
{
public void consolePrinter(int i)
{
Console.WriteLine(i);
}
}
class Test
{
static void Main()
{
MyClass cls = new MyClass();
Printer p = cls.consolePrinter;
}
}
Next chapter...
What you will learn in the next chapter:
- How to use multicast delegate
- Example to create multicast delegate
- Subtract delegate
- Use new operator to create delegate