I recently started digging into C# but I can’t by my life figure out how delegates work when implementing the observer/observable pattern in the language.
Could someone give me a super-simple example of how it is done? I have googled this, but all of the examples I found were either too problem-specific or too “bloated”.
The observer pattern is usually implemented with events.
Here’s an example:
See the linked article for a lot more detail.
Note that the above example uses C# 6 null-conditional operator to implement
DoSomethingsafely to handle cases whereSomethingHappenedhas not been subscribed to, and is therefore null. If you’re using an older version of C#, you’d need code like this: