what is the need of delegates?

Viewed 125

Iam not sure whether anyone ask the same question. But i couldnt find out any sources which are relevant for my doubt.

what is the need of delegates in real time programming? there are lot of steps needs to be done to implement it.

public delegate void SimpleDelegate();
  class TestDelegate
    {
        public static void MyFunc()
        {
            Console.WriteLine("I was called by delegate ...");
        }
        public static void Main()
        {
            // Instantiation
            SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);

            // Invocation
            simpleDelegate();
        }
    }

If re usability is a main reason (since no need to create instance) for using delegate, this can be achieved by other ways also. or this is the only advantages of using delegates? I know anonymous method do a better way than delegate. But is it providing anything than delegates other than simplification of steps. and how i can reuse anonymous method when the structure will be something like given below.

List<int> values = new List<int>() { 1, 1, 1, 2, 3 };
List<int> res = values.FindAll(delegate(int element)
    {
        if (element > 10)
        {
        throw new ArgumentException("element");
        }
        if (element == 8)
        {
        throw new ArgumentException("element");
        }
        return element > 1;
    });

I am confused. Please shed some lights on this.

2 Answers

With the use of Delegates, you can chain together any number of methods together, such that they can be called on when a single event is triggered. Delegates can be used to define callback methods. In Object-Oriented Development Projects, They can be very important where you want to call multiple methods at the same time. Many Senior Developers use these in different Applications of State Design patterns to call multiple methods when shifting to different concrete States.

Related