Dave Sexton's Blog

on software development using C# and the Microsoft .NET Framework
Welcome to Dave Sexton's Blog Sign in | Join | Help

Component Event Member Snippet

File Details
Downloads: 260 File Size: 2.6kB
Posted By: Dave Sexton Views: 491
Date Added: Mon, Mar 19 2007

My snippets are provided "as is", with no warranty of any kind, either express or implied.  Use at your own risk.

Creates the canonical event member declaration and corresponding method for invocation for a class that derives from System.ComponentModel.Component.  EventHandler is used as the delegate.  The code produced by this snippet is thread-safe.

Shortcut: eventc

For more information on my C# Code Snippets see my blog entry: Custom C# Code Snippets.  All of my snippets may be downloaded at once here.

Usage

This snippet is intended to be used as expansion or surrounds with from within the body of a class definition. The class must derive, directly or indirectly, from a class with a System.ComponentModel.EventHandlerList Events { get; } property defined with accessible scope. Otherwise, the property must be defined in the class itself.

It's useful for classes that derive from System.ComponentModel.Component or derived types such as the WinForms Control class. The ASP.NET Control class does not derive from System.ComponentModel.Component, however, it provides an EventHandlerList instance via a protected, read-only Events property. Therefore, this snippet is suitable for classes that derive from any FCL component or control.

Example Output

The following code illustrates this snippet's output using the default token values:

private readonly object TextChangedEvent = new object();

/// <summary>
/// Event raised after the <see cref="Text" />  property value has changed.
/// </summary>
[Category("Property Changed")]
[Description("Event raised after the Text property value has changed.")]
public event EventHandler TextChanged
{
  add
  {
    lock (TextChangedEvent)
    {
      Events.AddHandler(TextChangedEvent, value);
    }
  }
  remove
  {
    lock (TextChangedEvent)
    {
      Events.RemoveHandler(TextChangedEvent, value);
    }
  }
}

/// <summary>
/// Raises the <see cref="TextChanged" /> event.
/// </summary>
/// <param name="e"><see cref="EventArgs" /> object that provides the arguments for the event.</param>
protected virtual void OnTextChanged(EventArgs e)
{
  EventHandler handler = null;

  lock (TextChangedEvent)
  {
    handler = (EventHandler) Events[TextChangedEvent];
  }

  if (handler != null)
    handler(this, e);
}

Comments
No comments exist for this file.

Add Comment

Name (required)
Web Site (optional)
Comment (required)
Add
Powered by Community Server (Personal Edition), by Telligent Systems