Am I missing something here? How are null Event references changed by an operator?
class Foo
{
public event EventHandler<EventArgs> anEvent;
public Foo()
{
Console.WriteLine(anEvent == null); // true
anEvent += (sender, args) => { var i = 0; };
}
public static void Main(String[] args)
{
var a = new Foo();
Console.WriteLine(a.anEvent == null); // false
Console.ReadKey();
}
}
This actually runs through some compiler changes to your code. When you compile this, it creates a wrappers around anEvent for adding/removing handlers, very similarly to the way properties work. For example, in your class, when compiled, you would see (more or less):
class Foo
{
private EventHandler<EventArgs> anEvent;
public void add_anEvent(EventHandler<EventArgs> delegateToAdd)
{
//some code to make this safe, but basically calls-ish:
anEvent = System.Delegate.Combine(anEvent, delegateToAdd);
}
public Foo()
{
Console.WriteLine(anEvent == null); // true
//your += operator is converted to a call to "add_Event" instead
add_anEvent((sender, args) => { var i = 0; };);
}
}
Although an oversimplification of the underlying threadsafe code, this demonstrates how the null case is handled via the System.Delegate.Combine method which returns:
A new delegate with an invocation list that concatenates the invocation lists of a and b in that order. Returns a if b is null, returns b if a is a null reference, and returns a null reference if both a and b are null references.
EDIT: You can read up on the add and remove event accessors here: https://msdn.microsoft.com/en-us/library/aa664456%28v=vs.71%29.aspx
This page is about implementing custom event accessors, but a perhaps relevant passage on that page might be:
Each add-accessor-declaration and remove-accessor-declaration corresponds to a method with a single value parameter of the event type and a void return type. The implicit parameter of an event accessor is named value. When an event is used in an event assignment, the appropriate event accessor is used. Specifically, if the assignment operator is += then the add accessor is used, and if the assignment operator is -= then the remove accessor is used.
Even when you don't provide custom add and remove implementations, the compiler fills a basic one out for you. (Just like if you have blank get and set properties, the compiler fills a basic one out) In this sense, the "null" case is handled for you by calling these methods; you don't directly operate on the null event field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With