Team LiB
Previous Section Next Section

Anonymous Methods

Anonymous methods, new to version 2.0 of the framework, act a lot like C++ macros in that they allow you to create delegated methods that are inline when you add a new delegate to an event. One big difference is that you have type safety when you use anonymous methods.

In the following example, you can see that the anonymous delegate is automatically added to the event, without the need for a new method, as was used in the example in the previous section.

Code Example: Anonymous Methods
Start example
using System;

namespace Client.Chapter_8___Delegates_Events_and_Namespaces
{
      //Creates a method pointer
      public delegate void MyDelegateEventHandler(int i);
      class MyEventSubscriber
      {
            static void Main(string[] args)
            {
                  MyEventPublisher EventPublisher = new MyEventPublisher();


                  MyDelegateEventHandler MyAnonymousDelegate = delegate(int x)
                  {
                        Console.WriteLine("Anonymous Event FIRED!");
                  };

                  EventPublisher.MyEvent += MyAnonymousDelegate;

                  EventPublisher.DoSomething();
            }
      }
      public class MyEventPublisher
      {
            public event MyDelegateEventHandler MyEvent;
            public int DoSomething()
            {
                  MyEvent(5);
                  return 0;
            }
      }
}
End example

Team LiB
Previous Section Next Section