Tuesday 3 June 2014

Event Example in C#

public class MyClass
    {
      
        public delegate void LogHandler(string message); //Delegate
 
        
public event LogHandler Log;  //event
 
 
   
        public void Process()          //method used to start event
        {
            OnLog("Process() begin"); 
            OnLog
("Process() end");
        }

        protected void OnLog(string message)
        {
            if (Log != null)
            {
                Log(message);  
            }
        }

    }

public class TestApplication
    {
        static void Logger(string s) // call back method after event is called
        {
            Console.WriteLine(s);
        }

        static void Main(string[] args)
        {
         
            MyClass myClass = new MyClass();
 
           
            myClass.Log += new MyClass.LogHandler(Logger); 

                      // add  method which do process after event fire
          
 
            myClass.Process();

                   
// The Event will now be triggered in the Process() Method
         }
           

   }

More Details

No comments:

Post a Comment