How to Implement Event in Abstract Class and Raising from Derived Class in C#

Here I would not explain about the abstract class and events, I just wanted to show you how to implement events in abstract class and raised these events into derived class. I wrote a program to explain about implementation.

namespace AbstractEventHandling

{
    public abstract class
Work

    {
 
        public event EventHandler DoWork;
 

        public abstract void WorkDone();
        protected void RaiseDoWorkEvent( EventArgs e)
        {

            if (DoWork != null)
            {

                DoWork(this, e);

            }

        }

    }
   

   public class HandleWork :Work

    {
       public override void WorkDone()

       {

           Console.WriteLine("Work Successfully Done");

       }

       public void DoMywork()
       {

           base.RaiseDoWorkEvent(EventArgs.Empty);
           Console.WriteLine("Event Raised");

       }

    }
    

    class Program

    {
        static void Main(string[] args)

        {

            HandleWork h = new HandleWork();
            h.DoMywork();

            h.WorkDone();

            Console.ReadKey(true);

        }
    }

}
 

What's happening there we create a simple abstract class named Work; class that contains an abstract method named WorkDone. We also declare an event handle DoWork which is being raised inside the RaiseDoWorkEvent method. We create another class called HandleWork inherits from Work Class. We implement the abstract method WorkDone() here and create DoMywork() method to raise the base class event. You can also declare any event as abstract and override this event into derived class.

Write in base class

public abstract event EventHandler DoWork;

write and derived class

public override event EventHandler DoWork;

Image1.jpg