Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Develop a C# program that includes a delegate named “ Start ” that passes a m

ID: 3685459 • Letter: 1

Question

1. Develop a C# program that includes a delegate named “ Start ” that passes a method with a single argument.

2. The program should include at least two calls to a method that accepts the delegate with different value in the argument.

3. Based on an entry by the user at the keyboard , the program should execute one of two (or more) methods to simulate the “ start ” of something by calling for the respective delegate to be sent to the method.

The subject is left up to you but it should be more than simply displaying a string on the console. Please be creative and please make judicious use of comments so that I actually understand what's going on.

Explanation / Answer

Solution: See the code below

----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace delegatedemo
{
    class Program
    {
        //declaration of delegate
        public delegate void Start(int value);

        //definition of a method to be called through delegate
        public static void IncrementValueByOne(int value)
        {
            System.Console.WriteLine("Passed value:" + value+", now incrementing by one...");
            value++;
            System.Console.WriteLine("New value after increment:" + value);
        }

        //definition of another method to be called through delegate
        public static void IncrementValueByTwo(int value)
        {
            System.Console.WriteLine("Passed value:" + value + ", now incrementing by two...");
            value=value+2;
            System.Console.WriteLine("New value after increment:" + value);
        }

        static void Main(string[] args)
        {
            //Read value from keyboard
            Console.WriteLine("Enter a value:");
            int value = int.Parse(Console.ReadLine());
            Console.WriteLine("Entered Value:"+value+" ");

            //Instantiate the delegate
            Start handler = IncrementValueByOne;

            //Call the delegate
            Console.WriteLine("Calling delegate...");
            handler(value);
            Console.WriteLine("Delegate calling over. ");

            //Reinstantiating the handler
            handler = IncrementValueByTwo;

            //Call the delegate second time
            Console.WriteLine("Calling delegate again, but with a different method...");
            handler(value);
            Console.WriteLine("Delegate calling over.");

            //For holding the screen
            int a=Console.Read();
        }
    }
}

-----------------------------------------------------