Subscribing for events using lambda expressions
In C#, an object or a class can be used to inform other objects or classes when something happens, which is known as an event. There are two kinds of classes in the event, they are publishers and subscribers. The publisher is a class or object that sends (or raises) the event, while the subscriber is a class or object that receives (or handles) the event. Fortunately, lambda expressions can also be used to handle events. Let's take a look at the following code to discuss events further:
public class EventClassWithoutEvent { public Action OnChange { get; set; } public void Raise() { if (OnChange != null) { OnChange(); } } }
The preceding code can be found in the EventsInLambda.csproj
project. As we can see, a class named EventClassWithoutEvent
has been created in the project. The class has a property named OnChange
. This property's role is to store the action that subscribes the class and will be...