June 5, 2007
Hi Guys
I got the following program from the website. Address is given. I couldn’t understand the following code in the program. Please anybody explain.
ph = (ProcessHandler) Delegate.Combine(ph, new ProcessHandler(Process));
Thank you
//Delegates:Multicasting
//http://www.java2s.com/Code/CSharp/Language-Basics/DelegatesMulticasting.htm
using System;
public class DelegatesMulticasting
{
delegate void ProcessHandler(string message);
static public void Process(string message)
{
Console.WriteLine("Test.Process(\"{0}\")", message);
}
public static void
{
User user = new User("George");
ProcessHandler ph = new ProcessHandler(user.Process);
ph = (ProcessHandler) Delegate.Combine(ph, new ProcessHandler(Process));
ph("Wake Up!");
}
}
public class User
{
string name;
public User(string name)
{
this.name = name;
}
public void Process(string message)
{
Console.WriteLine("{0}: {1}", name, message);
}
}
/*
George: Wake Up!
Test.Process("Wake Up!")
*/
Posted Jun 6, 2007, 10:05 AM
Thank you for your help Jan Montano
Jan MontanoPosted Jun 5, 2007, 11:27 PM
ph = new ProcessHandler(user.Process);
// when you call ph("Wake Up!") at this time, it will only output George: Wake up!
ph = (ProcessHandler) Delegate.Combine(ph, new ProcessHandler(Process));
// calling this adds the function DelegatesMulticasting.Process to the already existing User.Process
// in effect, calling ph("Wake Up!") after this line will execute two functions. the User.Process & DelegatesMulticasting.Process. thus output will be
George: Wake Up!
Test.Process("Wake Up!")
(ProcessHandler) just casts the result of Delegate.Combine(ph, new ProcessHandler(Process))so that it can be assigned to ph
additional reference:
understanding delegates in c#