I’m having some real confusion about events in c#… if I have this code in an interface:
Event OnBeforeSaving(ByVal Sender As TEntity, ByVal EventArgs As CancelEventArgs)
How should it be in c#? When I run it through a converter it gives me this
event OnBeforeSavingEventHandler OnBeforeSaving;
delegate void OnBeforeSavingEventHandler(TEntity Sender, CancelEventArgs EventArgs);
I’m not sure if I understand what is going on… in my head the code should be combined. Is this correct?
event OnBeforeSaving(TEntity Sender, CancelEventArgs EventArgs);
No. In VB.NET, you can combine this on a single line. The Event keyword allows you to specify the full signature of the delegate type being handled.
In C#, however, you need to explicitly tell the event which type of delegate it will use. If it’s not a standard delegate type, then you have to declare the delegate, as well. This is what your converter is doing for you.
That being said, in this case, this:
Probably should be replaced with this:
This is because there is a built-in
EventHandler<T>type in the framework, that follows the suggested pattern for events, which specifies that the sender should be an System.Object, and the EventArgs should be a subclass of EventArgs. This is not quite the same as your VB.NET code, however, since you were restricting the sender to aTEntitytype.Even better would be to use the built-in CancelEventHandler type:
This is basically identical to
EventHandler<CancelEventArgs>, but more expected, since there is a framework event handler type specifically for cancellation.