I am kind of tired of having all this useless noise in my code:
private void RaiseSomeOtherEventIfItIsNotNull()
{
if (this.SomeOtherEvent != null)
{
this.SomeOtherEvent(this, EventArgs.Empty);
}
}
In 99.9% of the cases I don't care if someone attached to it or if it is null or not. Just raise the event! I really don't get it why the c# compiler makes me write all this noise.
So I though I could maybe declare an event like this:
public event EventHandler SomeOtherEvent = delegate { };
this would allow me to get rid of the useless null check and the useless Raise* Method. I could just always do:
this.SomeOtherEvent(this, EventArgs.Empty);
Now when I compare the standard approach with "my" approach in Lutz Röder's Reflector I see some signigicant differences. The compiler has overriden Add{}
and Remove{}
there is an extra static instance of the anonymous delegate:
[CompilerGenerated]
private static EventHandler CS$<>9__CachedAnonymousMethodDelegate1;
and there is this:
.method private hidebysig static void <.ctor>b__0(object, class [mscorlib]System.EventArgs) cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
.maxstack 8
L_0000: nop
L_0001: ret
}
Now my question: Do you seen any issues or disadvantages in decalring events with a default initialization like this?