How to Use “add” and “remove” Contextual Keywords of C# (C Sharp)

Most of you might be familiar with delegates and how they are associated with events. In addition to these concepts, do you know that you can wrap events using event accessors? If not, then this article will help you in understanding how and why to use event accessors.

Event accessors are represented by the contextual keywords add and remove. To start with, how do you declare and define an event? Here is an example for it:
public EventHandler sampleEvent;

When you compile this code, the equivalent compiler generated code will be:

public event EventHandler sampleEvent {
add {
sampleEvent += value;
}
remove {
sampleEvent -= value;
}
}

You have not written any explicit add and remove methods in your code, but the compiler has generated it. What would be the purpose of these methods? These methods are called event accessors. You have an event and you subscribe to the event using += operator and unsubscribe to the event using -= operator. Whenever you use += on this event, its corresponding add method will be triggered and when you call -= on this event, remove method will be called. This is happening implicitly.

However you can write these methods explicitly in your code. When you write the method, it overrides the automatically generated add and remove methods. If your explicit code does the same job as that of compiler generated code, then it doesn’t solve any purpose. You should explicitly code these methods only when it does some additional job when compared to the code generated by the compiler. What additional jobs can be done using add and remove methods? Here is the list:

• Debugging – You can provide additional debugging information in add and remove accessors. Here is the sample code:

public event EventHandler sampleEvent {
add {
Debug.WriteLine(‘Subscribing for the Event”);
sampleEvent += value;
}
remove {
Debug.WriteLine(‘Subscribing for the Event”);
sampleEvent -= value;
}
}

• Encapsulating Private Event – When you deal with classes, the common guideline you follow is to declare a class member as private and access it using get and set accessors with public visibility. By doing so you ensure encapsulation of data wrapped in the class. Same condition holds true for events as well. Consider the following example:

class sampleClass {
public event EventHandler sampleEvent;
}

In this example, you have declared sampleEvent as public. sampleEvent is now a class member which can be accessible by any subscriber who is listening to subscribe the event. This is not a recommendable approach. You should always have a private event that is wrapped with public accessors. Here is the modified example illustrating it:

class sampleClass {
private event EventHandler samplePrivateEvent;
public event EventHandler samplePublicEvent {
add {
samplePrivateEvent += value;
}
remove {
samplePrivateEvent -= value;
}
}
}

In this example, you have a private event called samplePrivateEvent. You wrap this event using the accessors of a public event called samplePublicEvent.

• To Store Events – Event occurrence is generally not stored. However if you wish to store and keep track of the event subscription and unsubscription, then you can very well do it using add and remove event accessors. Here is a sample code wherein the event subscription/unsubcription is maintained in a list:

class sampleClass {
private List<EventHandler> eventsList = new List<EventHandler>();
public event EventHandler sampleEvent {
add {
eventsList.Add(value);
}
remove {
eventsList.Remove(value);
}
}
}

• To Implement An Interface Which Declares The Event – In the examples discussed so far, you have declared event inside a class. You also have an option to declare event inside an interface. In such case, when you implement the interface you can wrap event of the interface using event accessors of the class that implements the interface. This scenario is illustrated in the example shown below:

public interface sampleInterface {
event EventHandler sampleEvent;
}
class sampleClass : sampleInterface {
private EventHandler privateEvent;
event EventHandler sampleInterface.sampleEvent {
add {
privateEvent += value;
}
remove {
privateEvent -= value;
}
}
}

Note that there is one constraint that has to be strictly enforced when wrapping events using event accessors. The constraint is that you should implement both the methods together. If you implement add method in your code but you didn’t deal with remove method or vice versa then you will end up in compilation error. Such an example is mentioned below:

class sampleClass {
private event EventHandler samplePrivateEvent;
public event EventHandler samplePublicEvent {
add {
samplePrivateEvent += value;
}
}
}

In this example, you have explicitly coded add method but remove method is not mentioned. On compilation this will end up in the error CS0065 stating “event property must have both add and remove accessor”.

| How does Yield Keyword of C# Use Lazy Evaluationm: Reference Types |How to Create Iterator to Process Generic List in C# | How to Use “add” and “remove” Contextual Keywords of C# | How to Use ForEach with Arrays in C# |Illustration of Operator Keywords (as, is) with Examples in C# | Illustration of Operator Keywords (new, sizeof) with Examples in C# |Illustration of Operator Keyword stackalloc with Examples in C# |Illustration of Operator Keywords (true, false) with Examples in C#|Illustration of Operator Keyword typeof with Examples in C# |List of Contextual Keywords in C#|


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.