CSharpFeeds - All your C# feeds in one place.

Sponsors

Saturday, December 22, 2007

Delegates through the ages

by gavin via elephantsintheroom.org on 12/22/2007 4:36:00 PM

The following code gives examples of subscribing to an instance of a void, parameterless delegate using

  1. a 'named' method (C# 1.0 and above)
  2. an anonymous method (C# 2.0 and above)
  3. a lambda expression (C# 3.0)
using System;
namespace RationalExpression
{
    class Program
    {
        //declare the delegate
        delegate void MinimalDelegate();
 
        static void Main(string[] args)
        {
            //create instance of the delegate
            MinimalDelegate instanceOfMinimalDelegate;

            //1. subscribe a named method 
            instanceOfMinimalDelegate = NamedMethod;

            //2. subscribe an anonymous method 
            instanceOfMinimalDelegate += delegate
                       {
                           Console.WriteLine("Anonymous method.");
                       };

            //3. subscribe using a lambda expression 
            instanceOfMinimalDelegate += () =>
            {
                Console.WriteLine("Lambda expression.");
            };

            //call all subscribers
            instanceOfMinimalDelegate();

            Console.ReadLine();
        }
        static void NamedMethod()
        {
            Console.WriteLine("Named method.");
        }
    }
}
email it!bookmark it!digg it!

Original Post: Delegates through the ages

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us