Where did use delegates in your project - Part 1

Where did you use delegates in your project?
or
How did you use delegates in your project?
or
Usage of delegates in a Real Time Project?

This is a very common c sharp interview question. Delegates is one of the very important aspects to understand. Most of the interviewers ask you to explain the usage of delegates in a real time project that you have worked on.

Delegates are extensively used by framework developers. Let us say we have a class called Employee as shown below.

Employee Class

Delegates Example Video - Part 1

Click here for Delegates Example Video - Part 2
The Employee class has the following properties.
1. Id
2. Name
3. Experience
4. Salary

Now, I want you to write a method in the Employee class, which can be used to promote employees. The method should take a list of Employee objects as a parameter, and should print the names of all the employees who are eligible for a promotion. But the logic, based on which the employee gets promoted should not be hard coded. At times, we may promote employees based on their experience and at times we may promote them based on their salary or may be some other condition. So, the logic to promote employees should not be hard coded with in the method.

To achieve this, we can make use of delegates. So, now I would design my class as shown below. We also, created a delegate EligibleToPromote. This delegate takes Employee object as a parameter and returns a boolean. In the Employee class, we have PromoteEmpoloyee method. This method takes in a list of Employees and a Delegate of type EligibleToPromote as parameters. The method, then loops thru each employee object, and passes it to the delegate. If the delegate returns true, then them Employee is promoted, else not promoted. So, with in the method we have not hard coded any logic on how we want to promote employees.



In Part 2 we will see how to consume, the Employee class that we have created.

19 comments:

  1. Couldn't understand clearly.I can achieve the same without delegate i.e I will write
    Promote(Employee employee) methode in Employee class and call this methode in for loop to check whether employee is eligible or not.

    ReplyDelete
  2. If you use Promote(Employee employee) method instead of the delegate EligibleToPromote(Employee EmployeeToPromote), you will have to hard code the logic based on which you want to promote the Employee. Where as when you use the delegate, you can define the logic in a seperate method and pass that method as a parameter to the delegate. So, if you look at the example, we have not hard coded the logic on how we want to promote the employee. Instead we just depend on the delegate's boolean value. So, if the method, the delegate is pointing to, returns true, we will promote the employee else we will not. So, the delegate in the above example, is allowing the users of the Employee class, to define their own logic on how they want to promote their employees.

    ReplyDelete
    Replies
    1. Hi venkat
      In Case of delegate also we have to hard code the logic in the method which we are passing to delegate.
      eg- bool Promote(Employee emp)
      {
      if(emp.sal>10000)
      return true;
      else
      return false;
      }

      Now using delegate
      Eligibetopromote=Promote;

      now calling Promote using delegte
      Eligibetopromote(employee);

      bool Promote(Employee emp)
      {
      if(emp.sal>10000)
      return true;
      else
      return false;

      }

      In Both Cases we have to write the logic in Promote method so why to use delegate.

      Delete
    2. Promote() method is in the client code, so the clients of your framework class can write any logic they want. Different clients of your class can use different logic.

      Delete
  3. I would use interface instead.

    ReplyDelete
  4. Venkat, it would be helpful If you can add a piece of code to show how this delegate is calling a method which has some logic to promote the Employee..

    ReplyDelete
  5. Excellent venkat we have got it....

    ReplyDelete
  6. The link below shows how the delegate "EligibleToPromote" can be used to call a method that has some logic to promote the Employee.

    Delegate with an example

    ReplyDelete
  7. A good example, however things are better than before with c# 4.0, there are lambda expressions and generic methods, do do the same job!

    ReplyDelete
  8. Could have been better! You should have shown how the method names are passed as parameters to the static function "PromoteEmployee", depending on the criteria that you had mentioned above!

    ReplyDelete
  9. Totally agreed on the way Venkat has explained in the comment. It was helpfull quite a bit. It would be great if there is a sample code how the employee would be promoted based on two different criterias. It would be enogh with just how to consume PromoteEmployee method using just 2 employees who would be promoted on 2 different criteria.

    Thanks in Advance...

    ReplyDelete
  10. Part two of this answer has the complete implementation / consumption of the deligate

    ReplyDelete
  11. i got confuse with the name of object , hahaha peace,,,, becoz you give the name like IsPromotable and isPromotable, same meaning but different letter

    ReplyDelete
  12. In case of the conditional methods understood but what is the method is not based on any condition. Say there is a class Employee and 2 other classes FullTimeEmployee and PartTimeEmployee derived from the employee class. Here the FullTimeEmployee and PartTimeEmployee contains their respective CalculateSalary method which returns float value and accepting worked duration as its parameter. These both methods have same signature. Now if we want these methods to send as parameter through delegate to some other place how can we make that. Overall I need to understand how can we use delegate when there is no conditional statement in the referred method and the method returns some value.

    ReplyDelete
  13. Let's look into the Practical usages of Delegates.
    When we talk about the delegates, first thing comes to over mind is event handling. We use delegates to implement the event and events are subscribed to a method. So is it practical usage in the current era of WPF and Prism application? - Definitely not.
    If you see the WPF applications event handling is done using ICommand. That is creating a command and initializing in the view model and accessing it in XAML application.
    So the practical use of delegates comes in subscriptions like collectionChanged event. For example I have a List when List changed I need to call a method to dosomething. I use
    var tradeList = new List();
    tradeList.CollectionChanged += DoSomething

    ReplyDelete
  14. In Case of delegate also we have to hard code the logic in the method which we are passing to delegate, but !!!!!!!!!!!!!!!!!!!!!!
    Our Employee class is 100% reusable with the implementation of delegate.

    ReplyDelete
  15. Venkat Sir Please share the usage of delegate and annonyms delegate.
    most of the people asks where you can use in your project .I understand how can we use but not benefits.

    ReplyDelete
  16. iam new to delegate,
    as per my knowledge delegates are reference pointer to methods.
    but here your referring to a class,can we do like this?

    ReplyDelete
  17. To the promoteEmployee method, what if we pass only the employees that needs to be promoted.In that case we will 1.Not have to write logic inside our promoteEmployee method
    2.Adhere to single responsibility principle

    ReplyDelete

If you are aware of any other C# questions asked in an interview, please post them below. If you find anything missing or wrong, please feel free to correct by submitting the form below.

 
Disclaimer - Terms of use - Contact Us