If you like to create custom delegates you would use the delegate keyword in lowercase.
What can you do with the actual Delegate Class? Wh
One of the things the Delegate class can be used for is more control when invoking event handlers. For example, with normal event processing, an exception in any event handler will prevent any later event handlers from being called. You can alter that behavior by using the Delegate class to manually invoke each event handler.
using System;
namespace DelegateClass
{
class EventSource
{
public event EventHandler TheEvent;
internal void RaiseEvent1()
{
EventHandler handler = TheEvent;
if (handler != null)
handler(this, EventArgs.Empty);
}
internal void RaiseEvent2()
{
EventHandler handler = TheEvent;
if (handler == null)
return;
Delegate[] handlers = handler.GetInvocationList();
foreach (Delegate d in handlers)
{
object[] args = new object[] { this, EventArgs.Empty };
try
{
d.DynamicInvoke(args);
}
catch (Exception ex)
{
while (ex.InnerException != null)
ex = ex.InnerException;
Console.WriteLine(ex.Message);
}
}
}
}
class Program
{
static void Handler1(object sender, EventArgs e)
{
Console.WriteLine("Handler1");
}
static void Handler2(object sender, EventArgs e)
{
Console.WriteLine("Handler2");
throw new InvalidOperationException();
}
static void Handler3(object sender, EventArgs e)
{
Console.WriteLine("Handler3");
}
static void Main(string[] args)
{
EventSource source = new EventSource();
source.TheEvent += Handler1;
source.TheEvent += Handler2;
source.TheEvent += Handler3;
try
{
source.RaiseEvent1();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("-------------------");
source.RaiseEvent2();
}
}
}