C Sharp Method Group Conversions

// The following is a simple example of event handlers without having to declare new’s 

using System;

namespace DelegateConsole
{
    public class SimpleMaths
    {
        public delegate void MathsMessage(string msg);
        public event MathsMessage ComputationFinished;

        public int Add(int x, int y)
        {
            ComputationFinished(“Adding Complete”);
            return x + y;
        }
        public int Subtract(int x, int y)
        {
            ComputationFinished(“Subtracting Complete”);
            return x – y;       
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            SimpleMaths s = new SimpleMaths();
            // Method group conversion – almost a delphi event handler
            s.ComputationFinished += ComputationFinishedHandler;
            Console.WriteLine(“10 + 10 is {0}”,s.Add(10,10));
            Console.ReadLine();
        }

        static void ComputationFinishedHandler(string msg)
        {
            Console.WriteLine(msg);
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s