Thursday, May 12, 2016

EventHandler with Generics in C#

In previous post, we saw the basic usage of EventHandler in C# here. In this post, we will see how to use EventHandler with generics in C#.

EventHandler With Generics

The EventHandler<TEventArgs> is a predefined delegate that represents an event handler method for event with data. We can use an object of class derived from EventArgs with such an EventHandler. This is essentially useful when we have an event where we want to use some data.


Event With Generics in C#


If we look at the implementation of EventHandler with generics, this is how it's defined:


public delegate void EventHandler<TEventArgs>(object sender, 
            TEventArgs e);

Suppose, we have a User class where we want to trigger an event whenever the user's name is updated. We want the event arguments to have the old user name and the new user name. On user name update, we want to print the old and new user name.

We will first create a new UserNameUpdatedEventArgs derived from EventArgs class.


public class UserNameUpdatedEventArgs : EventArgs
{
    public string OldUserName { get; set; }
    public string NewUserName { get; set; }
}

Next, here is the User class:

public class User {     public int userId;     public string name;     public User(int id, string username)     {         userId = id;         name = username;     }
    public void UpdateUserName(string username)     {         UserNameUpdatedEventArgs args = new            UserNameUpdatedEventArgs();         args.OldUserName = name;         args.NewUserName = username;         OnUserNameUpdated(args);     //event          name = username;     }
    protected virtual void OnUserNameUpdated(           UserNameUpdatedEventArgs e)     {         EventHandler<UserNameUpdatedEventArgs> handler =                 UserNameUpdated;         if (handler != null)         {             handler(this, e);         }     }
    public event EventHandler<UserNameUpdatedEventArgs>        UserNameUpdated; }

Please note how the event args are set in the UpdateUserName method. We set the old and new user names in the UserNameUpdatedEventArgs object and pass it to the event. 

In order to use it in the main method, we simply create a handler and use it like this:

static void Main(string[] args) {       User user = new User(1, "Abhi");       user.UserNameUpdated += program_UserNameUpdated;       user.UpdateUserName("Abhi Jain");       Console.ReadLine(); }
static void program_UserNameUpdated(object sender,       UserNameUpdatedEventArgs e) {     Console.WriteLine("The user name was updated from           {0} to {1}.", e.OldUserName, e.NewUserName); }

The output looks like this:

The user name was updated from Abhi to Abhi Jain

Conclusion

So we saw how to use EventHandler with generics in this post. This is pretty useful when we need to pass in special data.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

No comments:

Post a Comment