views:

145

answers:

1

I'm trying to convert the below bit of code into VB (and obviously apply it to my own solution) that I took from this MSDN article

// The event. Note that by using the generic EventHandler<T> event type
// we do not need to declare a separate delegate type.
public event EventHandler<ShapeEventArgs> ShapeChanged;

//The event-invoking method that derived classes can override.
protected virtual void OnShapeChanged(ShapeEventArgs e)
{
    // Make a temporary copy of the event to avoid possibility of
    // a race condition if the last subscriber unsubscribes
    // immediately after the null check and before the event is raised.
    EventHandler<ShapeEventArgs> handler = ShapeChanged;
    if (handler != null)
    {
        handler(this, e);
    }
}

My conversion (applicable to my program) is as follows:

Public Event StatusChanged As EventHandler(Of StatusChangedArgs)

Protected Overridable Sub OnStatusChanged(ByVal e As StatusChangedArgs)
   Dim handler As EventHandler(Of StatusChangedArgs) = StatusChanged 'error here'
   RaiseEvent handler(Me, e)
End Sub

But I'm getting an error: Public Event StatusChanged(sender As Object, e As StatusChangedArgs) is an event and cannot be called directly. Use a "RaiseEvent" statement to raise an event. If I'm converting it correctly, this doesn't make sense, since it's copied right out of MSDN, who I think would be correct, so obviously I'm doing something wrong. Anyone have any ideas?

Thanks...

+6  A: 
RaiseEvent StatusChanged(Me, e)

nothing else is necessary. Null check is unncessarily in VB.NET. It's done by RaiseEvent internistically.


Response to comment:

In C#, you save the delegate in a local variable to prevent race conditions. If you call a null delegate in C#, you'll get a NullReferenceException. To prevent it, you check it to ensure it's not null. If you write it as:

if (StatusChanged != null) { 
   // another thread might set `StatusChanged` to null at this point
   // causing the next line to fail.
   StatusChanged(this, e);
}

However, since VB does all this stuff in RaiseEvent, it's not necessary to check for nulls and consequently, it's not necessary to make a local copy of the delegate.

Mehrdad Afshari
i thought about this too, but why would MS say that i need to create a temp variable? is it because this is being put in a base class?
Jason
ah, ok... thanks! :)
Jason