Think about it in terms of events. Suppose you have a class that does some processing in the list of elements, and for each element, someone consuming your class may be notified that the element has been processed (perhaps update the progress bar or update some other part of the system , no difference). Let's put the delegates aside for a second and see how we can implement this using interfaces:
public class MyClassThatDoesSomething { private List<string> list = new List<string>(); public void ProcessList() { foreach(var item in list) { ProcessItem(item);
Now say that someone is consuming this class:
var mc = new MyClassThatDoesSomething(); mc.ProcessList(); //how do I know when each one has been processed?
So, solve this problem, create an interface:
public interface IItemProcessed { void ItemProcessed(string item); }
Now we can reorganize our original class:
public class MyClassThatDoesSomething { private List<string> list = new List<string>(); public void ProcessList() { foreach(var item in list) { ProcessItem(item);
and the consumer of your class can now do this:
public class ProcessListener : IItemProcessed { public void ItemProcessed(string item) { Console.WriteLine(item);
Now that you understand this, you can think of delegates as mini-interfaces, and then you can change your original class:
public class MyClassThatDoesSomething { private List<string> list = new List<string>(); public void ProcessList() { foreach(var item in list) { ProcessItem(item);
and consumer:
var mc = new MyClassThatDoesSomething(); mc.Listener = s => { Console.WriteLine(s);
To summarize, you can think of delegates as how to give outsiders a simple “hook” to your code, to allow them to provide small pieces of logic (think about Linq and filtering the collection) or for callbacks / events like I’ve demonstrated above .