Where did use delegates in your project - Part 2


In Part 1, we have seen how to create our Employee class. If you have not read Part 1, please do so before reading this part.

So now, the client who uses the Employee class has the flexibility of determining the logic on how they want to promote their employees a shown below. First create the employee objects - E1, E2 and E3. Populate the properties for the respective objects. We then create an employeeList to hold all the 3 employees.


Delegates Example Video - Part 2

Click here for Delegates Example Video - Part 1
Notice, the private Promote method that we have created. This method has the logic on how we want to promote our employees. The method is then passed as a parameter to the delegate. Also note, this method has the same signature, as that of EligibleToPromote delegate. This is very important, because Promote method cannot be passed as a parameter to the delegate if the signature differs. This is the reason why delegates are called as type safe function pointers.


So if we did not have the concept of delegates, it would not have been possible to pass a function as a parameter. As Promote method in the Employee class makes use of delegate, it is possible to dynamically decide the logic on how we want to promote employees.

In C Sharp 3.0, Lambda expressions are introduced. So, you can make use of lambda expressions instead of creating a function, and then an instance of a delegate and then passing the function as a parameter to the delegate. The sample example rewritten using Lambda expressions is shown below. Private Promote method is no longer required now.


The output of the above program should be as below.
Employee Test 2 Promoted
Employee Test 3 Promoted

5 comments:

  1. Hi Venkat
    Please let us know how to create Generic Delegate. This question was asked in one interview. Thanks.

    ReplyDelete
  2. Hi Venkat,
    Do you sell book that contains all of the examples you showed in the video tutorial? I would definitely buy one!

    ReplyDelete
  3. Really clear explanation. Thank's big guy.

    ReplyDelete
  4. hi venkat can u please solve the above question using Func,Action delegate

    ReplyDelete
  5. Hi venkat, this example looks great, thanks ! . could you please give an example for "call Back" using delegate?? Thanks in advance...

    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