Spaghetti Spaghetti - 3 months ago 11
C# Question

When/Why would you use a EventHandler over just a regular Event?

Is there a difference in functionality of an using an EventHandler and just defining an Event?

Answer

These are two different things

event declares an event :

https://msdn.microsoft.com/en-us/library/8627sbea.aspx

EventHandler defines the method that an event will raise:

https://msdn.microsoft.com/en-us/library/system.eventhandler(v=vs.110).aspx

EventHandler<TEventArgs> is a convenient wrapper for your custom EventArgs:

https://msdn.microsoft.com/en-us/library/db0etb8x(v=vs.110).aspx

Different ways to subscribe to an event

using System;

namespace ConsoleApplication3
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // using a method
            MyEvent += Program_MyEvent;

            // using EventHandler, possible but not mandatory
            MyEvent += new EventHandler(Target);

            // using lambda syntax
            MyEvent += (sender, eventArgs) => { };

            // using delegate
            MyEvent += delegate (object sender, EventArgs eventArgs) { };

            // using delegate, signature is optional actually
            MyEvent += delegate { };
        }

        private static void Target(object sender, EventArgs eventArgs)
        {
        }

        private static void Program_MyEvent(object sender, EventArgs e)
        {
        }

        public static event EventHandler MyEvent;
    }

}