Dot Net For All

Why do we need delegates in C#

Hello Friends, In one of my previous article I have discussed about the delegates in C#. I have continued my discussion by explaining the different type of delegates provided in the .NET framework. But I have seen many developers wondering why should we use delegates in C# or vb.net in the .NET framework.

Though there are some point provided in the MSDN documentation but they can make you more confused. In this article I will explain those points with examples and additional points. And hopefully you should be very clear when and where to use delegate in C#.

Use and Need of Delegates in C#

Lets start a point by point discussion:

As we know that event are type of delegates and events are used to assign a handler to the delegate. And delegate is used to invoke the handler.

The observer design pattern is a very good example of the eventing design pattern. I have discussed the observer pattern with a very nice and simple example.

Encapsulation of static method. Are you crazy. How can we encapsulate a static method. Yes this is a very good example to have a utilization of the delegates in C# and .NET platform.

Suppose you have a static method in a class and you do not want to publicly expose it to outside world.

Above all you want to call that private static method from the outside of the class. How is it possible.

You can achieve the  same with the help of delegate. Below is a simple example.

Public static void Main(string[] argss)
        {
            Publisher newContainer = new Publisher();
            Subscriber firstSub = new Subscriber(newContainer);
            newContainer.Invoke();
        }
        public delegate void MyDelegate(object sender, EventArgs args);
        public class Publisher
        {
            public MyDelegate MyEvent { get; set; }

            public void Invoke()
            {
                MyEvent(this, new EventArgs());
            }
        }

        public class Subscriber
        {
            private Publisher container;
            public Subscriber(Publisher container)
            {
                this.container = container;
            }

            public void Subscribe()
            {
                container.MyEvent += Container_MyEvent;
            }

            private static void Container_MyEvent(object sender, EventArgs args)
            {
                Console.WriteLine("Called by " + sender.ToString());
            }
        }

Is the above code self explanatory. I hope it should be.

I have encapsulated the method Container_MyEvent(handler) of the Subscriber from outside world. But still I am able to call it using the delegate.

You can use the delegates if the caller of the method has no need to access any other methods, properties of the object.

Lets discuss the point with the above code example.

Caller(Publisher) in the above code is only interested in only one method of the Subscriber. The method is the handler(Container_MyEvent) of the event.

You can take one more real time example from the Button click event. Suppose if you are having a button object in any of your form. And you want to raise the click event on some handler.

You only need to assign a handler to the button handler. And the handler should be present in the class containing the button instance.

You want an easy composition over the clumsy inheritance implementation. If you are in no plan to implement the whole functionality of the interface in your class, you can always opt for delegates.

Following is a simple example of the same

public delegate void MyDelegate(object sender, EventArgs args);
        public class Publisher
        {
            private MyDelegate del;
            public void Subscriber(MyDelegate delPara)
            {
                del += delPara;
            }
            public void Invoke()
            {
                del(this, new EventArgs());
            }
        }

In the above code Publisher class is composed of the MyDelegate delegate. But what if we have to implement using interfaces.

Suppose you are making a program for a simple calculator. The calculator does the simple operation of addition, subtraction, multiplication and division.

Below is the simple code using the delegates.

public delegate int DoCalculate(int a, int b);
        public class Calculate
        {
            public int FieldA { get; set; }
            public int FieldB { get; set; }
            public int DoOperation(DoCalculate cal)
            {
                return cal(FieldA, FieldB);
            }
        }

        public class Calculator
        {
            Calculate cal = new Calculate();
            public void Calculation(string operation, int a, int b)
            {
                cal.FieldA = a; cal.FieldB = b;
                switch (operation)
                {
                    case "Addition":
                        cal.DoOperation(this.Addition); break;
                    default:
                        break;
                }
            }

            public int Addition(int A, int B)
            {
                return A + B;
            }
        }

Quite simple isn’t it. But  suppose if we have to achieve the same using by creating different classes or using interface.

I leave it to reader to complete the above class for other operations and understand the use of delegates in C# programming.

We have to create separate class for each operation.

And call it. Though the above code does not look good from SOLID design principles point of view.

Conclusion

If you are a .NET programmer, it is very important for you to learn the use of delegates in C# programming for the implementation point of view. And it is a very common question asked in every interview for .NET programmer job.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview