c# - public event EventHandler SomeEvent = delegate { }; -
i kind of tired of having useless noise in code:
private void raisesomeothereventifitisnotnull() { if (this.someotherevent != null) { this.someotherevent(this, eventargs.empty); } }
in 99.9% of cases don't care if attached or if null or not. raise event! don't why c# compiler makes me write noise.
so though maybe declare event this:
public event eventhandler someotherevent = delegate { };
this allow me rid of useless null check , useless raise* method. do:
this.someotherevent(this, eventargs.empty);
now when compare standard approach "my" approach in lutz röder's reflector see signigicant differences. compiler has overriden add{}
, remove{}
there static instance of anonymous delegate:
[compilergenerated] private static eventhandler cs$<>9__cachedanonymousmethoddelegate1;
and there 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 question: seen issues or disadvantages in decalring events default initialization this?
you've shown method, not class. method fine, imo - that's representing no-op handler. not problem.
an class surprising, idea it's changing add/remove behaviour... compiler always creating add/remove methods event, that's makes event.
personally think fine - alternative write extension methods, e.g.
public static void raise<t>(this eventhandler<t> handler, object sender, t args) t : eventargs { if (handler != null) { handler(sender, args); } } public static void raise(this eventhandler handler, object sender, eventargs args) { if (handler != null) { handler(sender, args); } }
then call
myevent.raise(this, args);
that work eventhandler
, eventhandler<t>
events.
Comments
Post a Comment