using System;
using System.Collections.Generic;
using System.Text;
namespace delegate_function
{
class mydelegates
{
public delegate void DAM(string str);
// delegates first or constructor first
// for the class constructor will be the first one to evoked
public mydelegates() { Console.WriteLine("Constructor evoked"); }
~mydelegates() { Console.WriteLine("Destructor evoked"); }
//create a method with delegate
public void process_request(DAM input)
{
if (input !=null)
{
input("Checked in Manas ");
Console.WriteLine(" First Process done : ");
}
if (input != null)
{
DateTime showtime = DateTime.Now;
input("Today is ");
Console.WriteLine(" Second Process done { 0:m } : " + showtime );
}
}
public static void call_process(string s)
{
if (s == "Manas")
{
Console.WriteLine(" You have admin right : " + s);
}
else
{
Console.WriteLine(" Thanks for visiting " + s);
}
}
}
class test
{
static void admin(string ns) { Console.WriteLine(ns); }
static void Main(string[] args)
{
// #2 implement a delegate with new key word just line a class
//what is different?
//a class holds a delegate/pointer to a method encapsulated
//stay idle till called by a method in that external class.
//since it is static method, you need to call like this
//(mydelegates.call_process);
mydelegates myd = new mydelegates();
mydelegates.DAM d_a_m = new mydelegates.DAM(mydelegates.call_process);
mydelegates.DAM dd = new mydelegates.DAM(admin);
Console.Write(" Admin's call : ");
myd.process_request(admin);
Console.Write(" Enter something : ");
string str = Console.ReadLine();
// #3 invoke a call through a delegate object
d_a_m(str);
Console.Write(" Hit Enter to Quit : ");
Console.ReadLine();
}
}
}
|
| Step 1:
|
| Step 2: shows the object with the namespace
|
| Step 3: Object created and constructor evoked
|
| Step 3: Checking on delegates
|
| Step 4: Now checking on another object derived from
delegate
|
| Step 5 Evaluationg a method with delegate in an external
class
|
| Step 6: Note carefully that cursor returns to the
output-location of that is, "admin" a static method.
Now as the line was processed, you would see the out put
|
| Step 7:
|
| Step 8: very similar fashion the second logical statement
was processsed
|
| Step 9: Below shows the completion of delegating a call to
admin
|
| Step 10: now you are entering another instance of the
delegate where you are sending a string to a method
|
| step 11
|
| step 12 The input is being delegated to a method that take
care of the input
|
| step 13: entering the if logical statement, since it is a
match we will see a print out of "You Have-----"
|
| Step 14
|
| step 15: Completing the delegation and back reporting to the
object d_a_m
|
| step 16:
|
| Below shows the outputs, when you are using .Net Frame work
2. 0 SDK; The last line "Destructor Evoked" would not be seen with Visual
Studio 2005 IDE.
|