namespace AnonymousMethods
{
public class MyClass
{
public delegate void MyDelegate(string message);
public event MyDelegate MyEvent;
public void RaiseMyEvent(string msg)
{
if (MyEvent != null)
MyEvent(msg);
}
}
class Caller
{
static void Main(string[] args)
{
MyClass myClass1 = new MyClass();
//Register event handler as anonymous method.
myClass1.MyEvent += delegate
{
Console.WriteLine("we don't make use of your message in the first handler");
};
//Register event handler as anonymous method.
//here we make use of the incoming arguments.
myClass1.MyEvent += delegate(string message)
{
Console.WriteLine("your message is: {0}", message);
};
//the final bracket of the anonymous method must be terminated by a semicolon.
Console.WriteLine("Enter Your Message");
string msg = Console.ReadLine();
//here is we will raise the event.
myClass1.RaiseMyEvent(msg);
Console.ReadLine();
}
}
}
Notice that when you use the anonymous methods you don't need to define any static event handlers. Rather, the anonymous methods are defined at the time the caller is handling the event.
Note: You are not required to receive the incoming arguments sent by a specific event. but if you want to make use of the incoming arguments you will need to specify the parameters defined by the delegate type (just like the second handler in the previous example).
Example:
myClass1.MyEvent += delegate(string message)
{
Console.WriteLine("your message is: {0}", message);
};
we're done, I hope you now have a good understanding of anonymous methods in C#.