views:

169

answers:

2

Say you have an event raiser method (OnXXX) that raises an event using the CancelEventArgs class is there anything wrong with having the OnXXX method return the value of e.Cancel?

For example:

Public Sub ProcessFiles(folder as DirectoryInfo)

    For each file in folder.GetFiles()
        If OnProcessingFile(New FileEventArgs(file)) Then
            .....ProcessFileCode
        Else
            Exit For
        End If
    Next

End Sub

Protected Function OnProcessingFile(ByVal e As FileEventArgs) As Boolean

    RaiseEvent ProcessingFile(Me, e)
    Return Not e.Cancel

End Function

Seems to me to be a cleaner solution than this:

Public Sub ProcessFiles(folder as DirectoryInfo)

    Dim e As FileEventArgs

    For each file in folder.GetFiles()

        e = New FileEventArgs(file)
        OnProcessingFile(e)

        If e.Cancel Then
            Exit For
        End If

        .....Process File Code

    Next

End Sub
+1  A: 

Probably because event dispatchers are usually implemented as delegates and the semantics of handling n functions each capable of returning a result, would be icky to say the least.

Allain Lalonde
But I'm not returning the value from n functions. I'm the value in EventsArgs after n functions.
Tim Murphy
OnProcessingFile is returning a value (the Return Statement), exactly how that value is computed is irrelevant.
Allain Lalonde
+5  A: 

The reason why has to do with the implementation of events in .Net. They are often of type MulticastDelegate which means there can be multiple subscribers to the event. So the RaiseEvent call calls N functions where N can be 0, 1 or >1. Having the event return a value only works as expected in the case where there is 1 subscriber.

In the case of 0, what should the CLR return?

In the case of >1 which delegate should win? I believe the current implementation dictates the last delegate will win. But what if the first says cancel but the last says don't cancel. Event arguments are the current best way to resolve this difference.

JaredPar
@JaredPar. But I'm not returning a value from the event, I'm returning a value from the EventArgs parameter. Can you explain to me what the differnce is between the 2 examples?
Tim Murphy
@Tim - But what if there are several subscribers to your event? What if one subscriber sets the Cancel property to true and another sets it to false? When you call If RaiseEvent ProcessingFile, there may be more than one event handler executed. What if they each set Cancel to a different value?
Chris Dunaway