|
![]() |
| delegate ret-type name(parameter-list); |
using System;
namespace testdelegate2
{
public delegate void helloworld();
class test
{
public static void method()
{
Console.WriteLine("hello, world!");
}
static void Main(string[] args)
{
helloworld dg = new helloworld(method);
dg();
Console.ReadLine();
}
}
}
|
| Example |
|
|
The example shown below contains a method,
|
using System;
using System.Collections.Generic;
using System.Text;
namespace delegate_example
{
// #1 delcare a delegate
/*
* use the keyword delegate
* name the method you will be encapsulating
* and its return type
*/
public delegate void delegate_a_method(string str);
//
class test
{
public static void process_request(string input)
{
string received = input;
Console.WriteLine("hello, user you entered : " + received);
}
[STAThread]
static void Main(string[] args)
{
// #2 implement a delegate with new key word just line a class
//what is different, as if class needs a parameter
delegate_a_method d_a_m = new delegate_a_method(process_request);
Console.Write(" Enter something :");
string str = Console.ReadLine();
// #3 invoke a call through a delegate object
d_a_m(str);
Console.ReadLine();
}
}
}
|
| Entering the program with F11
|
| next, creating object and instantiating a delegate
|
| requesting user's input
|
| Go through F11 steps.
|
| Delegate object is calling the method
|
| At this point if point string input with your mouse you will note
|
|
|
![]() |
|
|
|
|