Search This Blog

Tuesday, July 16, 2013

Logger class Delegate Example

C# > Delegate

Logger class Delegate Example

Example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public class LoggerClass
        {
            public delegate void LogHandler(string message); // Declare a delegate
            public void Log(LogHandler vLogHandler)
            {
                vLogHandler("Log begin");
                // do stuff ...
                vLogHandler("Log end");
            }
        }
        static void Logger(string s)
        {
            MessageBox.Show(s);
        }
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            LoggerClass mClass = new LoggerClass();
            LoggerClass.LogHandler mLogger = new LoggerClass.LogHandler(Logger);  // create an instance of the delegate and pointing to the logging function.
            mClass.Log(mLogger); // delegate will be passed to the Log() function.
        }
    }
}