Many times in interviews we face the question, “What problem does delegates solve?” Even though we know how to create and use Delegates we can’t convince the interviewer. I have also searched a lot and found many articles, below is the summary based on my knowledge. Hope this will give readers an in-depth understanding on delegates.
What is delegate?
Delegate in C# represents function pointers. Delegates are examples of encapsulation. It will encapsulate reference to a method inside itself. You are free to put any method which matches signature and it will get called when your delegate will gets called.
Now let’s come to the point
Problem 1
We have a windows form, on that form I have a grid. Now we also have a user control and on UC we have one Button.

Note: I am not saying this problem will only get solved by delegates; rather delegates are helpful in such a situation.
Solution: I will use publisher and subscriber pattern in this case using Delegates.
Step 1: I will create a Delegate and Event under user control as mention below:
publicdelegatevoidButtonClickedEventHandler(objectsender,EventArgs e);
publiceventButtonClickedEventHandlerOnUserControlButtonClicked;
Step 2: Will expose the event on button click on UC as mention below:
- if (this.OnUserControlButtonClicked != null)
- {
- this.OnUserControlButtonClicked(GetDataTable(), e);
- }
- privateDataTableGetDataTable()
- {
- DataTable table = newDataTable();
- table.Columns.Add("Name", typeof(string));
- table.Columns.Add("Class", typeof(int));
- table.Columns.Add("Gender", typeof(char));
- table.Rows.Add("Nishant", 1, "M");
- table.Rows.Add("Mittal", 2, "M");
- return table;
- }
Step 3: On form load I will create an object of user control, at it on the form and initialize its event as well as mention below:
- DataobjCntrol = newData();
- objCntrol.OnUserControlButtonClicked+=newData.ButtonClickedEventHandler(objCntrol_OnUserControlButtonClicked);
- this.panel1.Controls.Add(objCntrol);
- voidobjCntrol_OnUserControlButtonClicked(object sender, EventArgs e)
- {
- DataTabledt = (DataTable)sender;
- dgv_Btn.DataSource = dt;
- }




Join the conversation! Your thoughts help the community grow.