神刀安全网

Events using EventHandler in C#

In today’s post, I will be discussing Events using Event Handler in C#. This is in continuation with the previous week posthere.

Events without using Delegates explicitly

Last week we discussed what events are and how to use them in our application. We saw how to use events using delegateshere. That post was more to show what’s going on behind the scenes. The .NET framework has special guidelines on the delegates that can be used for events. The delegate type should have an object parameter and EventArgs parameter and should return void. So the .NET framework has defined a special delegate type called EventHandler for this purpose.

So the last week’s example, if we were using EventHandler, will be as follows:

public class ListWithChangedEvent : ArrayList {     public event EventHandler Changed;     protected virtual void OnChanged(EventArgs e)     {             if (Changed != null)                 Changed(this, e);      }      public override int Add(object value)     {         int i = base.Add(value);          OnChanged(EventArgs.Empty);         return i;     }      public override void Clear()     {         base.Clear();         OnChanged(EventArgs.Empty);     }      public override object this[int index]     {         set         {             base[index] = value;             OnChanged(EventArgs.Empty);         }     } }

There is no delegate being used explicitly and we just used EventHandler.

Internally, the EventHandler looks like as follows:

public delegate void EventHandler(object sender, EventArgs e);

So, to use the list we can do it the same way as previous post mentioned above:

static void Main(string[] args) {      ListWithChangedEvent list = new ListWithChangedEvent();      list.Changed += ListChanged;      list.Add("item 1");      list.Clear();      Console.ReadLine(); }  private static void ListChanged(object sender, EventArgs e) {      Console.WriteLine("This is called when the event fires without delegate."); }

The list triggers event anytime the list items are changed.

Conclusion

So we saw a simple example of delegates usage using EventHandler. Using EventHandler helps us follow the .NET framework guidelines and adhere to the standard. It’s good to know how the delegates work behind the scenes.

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 :)

Follow @abhijain369

Reference:  MSDN

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Events using EventHandler in C#

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址