Handling Events in c# .NET

To handle an event you need to subscribe to it by providing an event handler method whose return type and parameters match that of the delegate specified for use with the event. The following example uses a simple timer object to raise events, which results in a handler method being called.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
namespace w3m
    class Program
        static int counter = 0;
        static string displayString = "This string will appear one letter at a time. ";
        static void Main(string[] args)
            Timer myTimer = new Timer(100);
            myTimer.Elapsed += WriteChar;
        static void WriteChar(object source, ElapsedEventArgs e)
            Console.Write(displayString[counter++ % displayString.Length]);

Enjoyed this post? Share it!


Leave a comment

Your email address will not be published.