Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What use cases exist for non-static private or protected events?

Tags:

c#

.net

vb.net

What purpose do protected or private (non-static) events in .NET really serve?

It seems like any private or protected event is more easily handled via a virtual method. I can (somewhat) see the need for this in static events, but not for normal events.

Have you had a use case before that clearly demonstrates a need or advantage for a non-static protected or private event?

like image 396
Reed Copsey Avatar asked Sep 25 '09 20:09

Reed Copsey


1 Answers

Here's a slightly bizarre but real-world scenario I implemented once. You have machine-generated and user-generated halves of a partial class. The machine-generated half contains code which wishes to inform the user-generated half when some event occurs. But the user-generated half might not care to do anything, or it might care to do rather a lot. It seems rude of the machine-generated half to require that the user-generated half implement a particular method in order to handle a message they don't have any interest in listening to.

To solve this problem, the machine-generated half could fire on a private event. If the user-generated half cares, it can subscribe the event. If not, it can ignore it.

This scenario is now addressed more elegantly by partial methods in C# 3, but that was not an option back in the day.

like image 68
Eric Lippert Avatar answered Oct 14 '22 12:10

Eric Lippert