"Better"? Well, doesn't contain a (specific) race condition, one does. MultiCastDelegate types are immutable and use value type semantics in all of the ways that matter (they are reference types however, see this and, more importantly, this), that's why you assign it first and then check. The problem is that:
// this evaluates to true...
if(SomeEvent != null)
{
// ...but before this line executes, the last
// subscriber detached, and now SomeEvent is null. Oops.
SomeEvent(this, e);
}
You should have asked "why would anyone use example #2?"
As an aside, this is a great place to use an implicitly typed variable (var
). Those delegate type names get long...
Also interesting is that a race condition still exists, it's just more subtle. What happens if a subscriber is removed after the assignment? Well, it will still get called, but there's really nothing (I know of) that you can do about it.