C# Delegates and Events—Events
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| C# Articles |
| edit |
Events
One of the most common uses of delegates in .NET is event handling. Events are useful for notifying objects of user interface events or state changes. The following example creates a Timer object that will fire an event every second. The Timer class is defined in the System.Timers namespace.
class DelegateDemo { static void Main(string[] args) { Timer t = new Timer(1000); t.Elapsed += new ElapsedEventHandler(Timer_Elapsed); t.Enabled = true; Console.WriteLine("Press enter to exit"); Console.ReadLine(); } static void Timer_Elapsed(object sender, ElapsedEventArgs e) { Console.WriteLine("tick"); } }
The Timer class contains the Elapsed event and fires it whenever its interval expires. In this example the Main method instantiates a Timer and registers an ElapsedEventHandler delegate with its Elapsed event.
In this example, the method invoked by the ElapsedEventHandler delegate is the Timer_Elapsed method. Following the convention of all event handling delegates, the ElapsedEventHandler delegate returns void and accepts two parameters. The first is a reference to the object that signaled the event and the second is a argument derived of EventArgs which stores pertinent information about the event.
|

