CSharp - Passing Data with Event Arguments

Introduction

To pass more information than EventArgs

  • Create a subclass of System.EventArgs.
  • Encapsulate the intended data with the event.

Create an instance of this class and pass it with the event.

Demo

using System;

public class JobNoEventArgs : EventArgs
{
    private int jobNo;
    public int JobNo
    {/*from   w  w  w.j  a v  a  2 s . c om*/
        get
        {
            return jobNo;
        }
        set
        {
            JobNo = value;
        }
    }
    public JobNoEventArgs(int jobNo)
    {
        this.jobNo = jobNo;
    }
}
class Publisher
{
    public delegate void JobDoneEventHandler(object sender, JobNoEventArgs args);
    public event JobDoneEventHandler JobDone;
    public void ProcessOneJob()
    {
        Console.WriteLine("Publisher:One Job is processed");
        OnJobDone();
    }
    protected virtual void OnJobDone()
    {
        if (JobDone != null)
            JobDone(this, new JobNoEventArgs(1));
    }
}
class Subscriber
{
    public void OnJobDoneEventHandler(object sender, JobNoEventArgs args)
    {
        Console.WriteLine("Subscriber is notified.Number of job processed is :{ 0} ", args.JobNo);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Publisher sender = new Publisher();
        Subscriber receiver = new Subscriber();
        sender.JobDone += receiver.OnJobDoneEventHandler;
        sender.ProcessOneJob();
    }
}

Result

Related Topic