Declare simple event
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| C# Code Snippets |
| See also |
| edit |
This C# code snippet declares an event with EventHandler using the default implementation for removing events and subscribing to events. We implement the IDisposable interface simply to have a reasonable excuse to throw an event.
public class MyClass : IDisposable { public event EventHandler Disposing; public void Dispose() { // release any resources here if (Disposing != null) { // someone is subscribed, throw event Disposing (this, new EventArgs()); } } public static void Main( ) { using (MyClass myClass = new MyClass ()) { // subscribe to event with anonymous delegate myClass.Disposing += delegate { Console.WriteLine ("Disposing!"); }; } } }