Call Events with Delegate in C#

Scenario: Call method of 2nd Class while calling method of 1st Class using delegates.
                       “Call friends when employee get promoted”

Example:
    delegate void PromoteDelegate(string eName);
    class Program
    {
        //PM
        static void Main(string[] args)
        {
            Friend f = new Friend();
            Employee e = new Employee();
            e.pd += new PromoteDelegate(f.CallWhenPromoted);
            e.Promoted("Mehul");

            //e.pd();
            Console.ReadLine();
        }
    }

    class Employee
    {
        public event PromoteDelegate pd;
        public void Promoted(string eName)
        {
            Console.WriteLine("Congratulation! Employee {0} 
            get promoted...",eName);
            Console.WriteLine("Calling Delegate...");
            pd("Mehul's friend");
        }
    }

    class Friend
    {
        public void CallWhenPromoted(string fName)
        {
            Console.WriteLine("Thanks for calling {0}...", fName);
        }
    }
  
Output:
            Congratulation! Employee Mehul get promoted...
            Calling Delegate...
            Thanks for calling Mehul's friend...

No comments:

Post a Comment