DEV Community

Debashish Pal
Debashish Pal

Posted on • Updated on

Solve the scenario - using Delegates & Interfaces in Dotnet

Use Case:

We have this hypothetical reporting system where 2 entities are involved Report Generator & Report.

Report Generator:

  1. Report generator would have a single behavior.
    • It should take 2 inputs as integers.
    • It Returns a string back as an output which is basically the report presentation.

(So, basically above 2 point forms the contract that need to be fulfilled by any report generator)

Report:

  1. Report should take report generator object or report generation logic in the form of function as an input.
  2. Give call to the report generator by passing input1 & input2.
  3. Get the string Output back from generator.
  4. Will have the functionality to write the Output to console or file system.

Whenever, I introduce a new Report Generator, neither Report entity nor existing Report Generator's, should be modified.

Take a pause

Think about the solution

?

Think again

Scroll down for the solution

...

...

...

...

...

...

Solution

Run the below code in Linqpad (https://www.linqpad.net/), to see it working.

Motivation

Generally every one understands the theoretical aspect of Delegates and Interfaces, but when it comes to actual use of the same, beginner's lacks the understanding of when such constructs need be used and in which scenario. This problem based illustration might be of some help to understand the concept better.

Happy Coding !!

Latest comments (0)