C# Rule CA1070 Explains Why Event Fields Should Never Be Declared Virtual
C# code analysis rule CA1070 warns developers against marking event fields as virtual, a practice that causes unpredictable behavior in inheritance hierarchies. When a virtual event is overridden in a derived class, the derived class creates its own separate backing field rather than truly replacing the base event, splitting subscribers into two disconnected channels. This means handlers attached via a base-class reference will never receive notifications raised through the derived event, leading to missed callbacks and hard-to-trace bugs. Because the C# language specification does not support true event overriding, the virtual modifier on events is inherently misleading and undermines binary compatibility. CA1070 recommends keeping events non-virtual and instead exposing virtual protected methods or virtual add/remove accessors when customization across subclasses is required.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in