Reputation: 1746
I am using a converter that converted the following VB code
Public Event Progress(ByVal Percent As Integer)
to C#
public delegate void ProgressEventHandler(int Percent);
private ProgressEventHandler ProgressEvent;
public event ProgressEventHandler Progress
{
add
{
ProgressEvent = (ProgressEventHandler) System.Delegate.Combine(ProgressEvent, value);
}
remove
{
ProgressEvent = (ProgressEventHandler) System.Delegate.Remove(ProgressEvent, value);
}
}
That seems quite a lot of code. I was expecting just these 3 lines.
public delegate void ProgressEventHandler(int Percent);
private ProgressEventHandler ProgressEvent;
public event ProgressEventHandler Progress;
and then later I invoke the event in this way
void OnProgress(int p) {
ProgressEvent?.Invoke (p);
}
So what exactly I need to know is what is the advantage of the Progress body (with add and remove). Should I stick to my own code or use the code by the converter? Which one is better?
Upvotes: 0
Views: 75
Reputation: 387677
Those System.Delegate.Combine
and System.Delegate.Remove
calls are just verbose ways of doing the following:
// combine
ProgressEvent += value;
// remove
ProgressEvent -= value;
Which turns the event member into the following:
private ProgressEventHandler ProgressEvent;
public event ProgressEventHandler Progress
{
add
{
ProgressEvent += value;
}
remove
{
ProgressEvent -= value;
}
}
And at that time, it’s equivalent to the auto-implemented event member:
public event ProgressEventHandler Progress;
So, this is essentially just a verbose way of defining the event and event handler, but which really means just the same. I assume that the converter that you were using just uses the verbose way to be able to handle non-standard solutions easier. And maybe it is generating this from the compiled IL, at which point this all looks more or less the same.
Btw. your expected code won’t work since the Progress
event and the handler ProgressEvent
are not linked (so if you want to split those members, you need to implement the event explicitly).
Upvotes: 2