c# - Implementing abstract event gives "Invocation of polymorphic field-like event" warning from ReSharper -
i have abstract base class following abstract event
public abstract class signalwrapperbase<t> : ireadonlysignal<t> { public abstract event action<ireadonlysignal<t>, sample<t>> updated; ... }
in implementation say
public class valuechangedsignal : signalwrapperbase<t> { public override event action<ireadonlysignal<t>, sample<t>> updated; ... }
and when in implementation valuechangedsignal
try perform following
if (updated != null) { updated(this, sample); }
i resharper warning: invocation of polymorphic field-like event.
i checked reasoning behind it, uses virtual
not abstract
in example:
public class base { public virtual event eventhandler myevent; } public class derived : base { public override event eventhandler myevent; public void somemethod() { var args = ...; myevent(this, args); } }
the above block of code uses overriding event declaration override implementation of add , remove methods on event. field exist in 2 separate instances - 1 in base , 1 in derived. consequence, when working derived, you're never instantiate base's myevent unless explicitly set value. and, result of that, behavior in case when event raised in base class differ in derived class.
i get 2 instances if virtual
. hiding base implementation actual implementation, however, when use abstract
never making base implementation, i? thought when use abstract on field forwarding implementation inheriting class, i.e., requiring user of base class implement abstract code.
is resharper giving me wrong warning? or misunderstanding something?
it's not false warning , resharper puts attention on fact your derived class can inherited , event overridden.
let's see example:
static void main(string[] args) { base b = new derived(); b.e += (sender, eventargs) => { console.writeline("event handled"); }; b.raise(); } abstract class base { public abstract event eventhandler e; public abstract void raise(); } class derived : base { public override event eventhandler e; public override void raise() { if (e != null) e(this, null); // resharper: invocation of polymorphic field-like events } }
result of main(): event handled
everything works expected: subscribed event e, raised event e , can see message event subscribtion on screen.
now, if inherit class derivedclass , override event this:
static void main(string[] args) { base b = new mostderived(); b.e += (sender, eventargs) => { console.writeline("event handled"); }; b.raise(); } class mostderived : derived { public override event eventhandler e; }
things change , main() puts out nothing.
it happens because there 2 private fields of event e in object b: 1 comes derived class , other mostderived. that's resharper warned about.
if you're sure derived class never inherited , event e overriden, mark derived sealed , resharper warning disappear.
Comments
Post a Comment