Generically Typed EventArgs

So I was fooling around the other day in Visual Studio, and I was making events for some of my classes. Specifically, these events were generated when a specific property would change values. I had already implemented the INotifyChanged interface, but I also wanted strongly linked events per property, because we all know as programmers that can be nice to have. I ran into a problem, though. The generic EventArgs didn't allow me to give the user the information on what the previous and new values were for the change event. And I really didn't want to have to create a derived class for specialized EventArgs for every property I was working with. So I wrote a generically typed EventArgs. You may already have something like this in your utility belt, and if so, bully for you! It is super handy! If not, I'll show you how to use the class in an example, and then I'll provide you the full source below.

public event EventHandler<TypedEventArgs> SomeIntChangedEvent;public void FireSomeIntChangedEvent(int oldValue, int newValue){    SomeIntChanged(this, new TypedEventArgs(oldValue, newValue));}
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace YourNamespaceHere{    ///  A typed event args class.     ///  Generic type parameter for the event arguments.     public class TypedEventArgs : EventArgs    {        #region Members        ///  The old value         private T oldValue;        ///  The new value         private T newValue;        #endregion        #region Properties        ///  Gets the old value.         ///  The old value.         public T OldValue        {            get            {                return this.oldValue;            }        }        ///  Gets the new value.         ///  The new value.         public T NewValue        {            get            {                return this.newValue;            }        }        #endregion        #region Constructor        ///  Constructor of a generic event argument.         /// The old value.        /// The new value.         public TypedEventArgs(T oldValue, T newValue)            : base()        {            this.oldValue = oldValue;            this.newValue = newValue;        }        #endregion        #region Overrides        ///  Convert this object into a string representation.         ///  A string representation of this object.         public override string ToString()        {            return string.Format("Old Values: {0} - New Value: {1}", this.OldValue, this.NewValue);        }        #endregion    }}

This article was updated on Wednesday, April 21, 2021