SIGN UP MEMBER LOGIN:    
ARTICLE

Anonymous methods in C#

Posted by Amr Monjid Articles | Visual C# March 06, 2008
This article discusses the anonymous methods as a new feature in .NET 2.0, it will show you how to associate a delegate directly to a block of code statements at the time of event registration.
Reader Level:
Download Files:
 

Introduction:

As you may know, if the caller want to respond to any event, it must create a method -(event handler) that matches the signature of it's associated delegate. Such method is only called by the event associated delegate object.

(if you don't know about delegates and events see my articles Delegates in C#, Events in C#).

Example:

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();
        myClass1.MyEvent += new MyClass.MyDelegate(myClass1_MyEvent);
        myClass1.RaiseMyEvent("Hiii");
    }
    //this method called only by MyDelegate
    public static void myClass1_MyEvent(string message)
    {
        //do some thing to respond to the event here
    }
}

As you can see, event handler methods such as (myClass1_MyEvent) are never called by any part of the application other than the invoking delegate so you need it only to handle you event.

You can associate a delegate directly to a block of code statements at the time of event registration. Such code is named anonymous method.

The next example will show you how to handle the events using anonymous methods:

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#.

Login to add your contents and source code to this article
share this article :
post comment
 

When using a event handler, we use the following code to remove the association from an event: myClass1.MyEvent-=myClass1_MyEvent; How do we do this when using Anonymous methods?

Posted by penna liu Mar 07, 2008
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Become a Sponsor