Event handler methods should be declared as private or protected
An event handler (like OnClickButton()) should be private and only called on event firing — or protected, as some designers (e.g. ASP.NET) generate it so sub-classes can call it.
How to fix
If another class needs to call the handler, find a structure matching the actual concept: the other class doesn't want to click a button, it wants to do what clicking the button also does.
CQLinq source
This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.
// <Name>Event handler methods should be declared as private or protected</Name>
// <Id>ND1808:EventHandlerMethodsShouldBeDeclaredAsPrivateOrProtected</Id>
warnif count > 0
from m in Application.Methods where
!(m.IsPrivate || m.IsProtected) &&
!m.IsGeneratedByCompiler &&
// A method is considered as an event handler if…
m.NbParameters == 2 && // … it has two parameters …
m.Name.Contains("Object") && // … of types Object …
m.Name.Contains("EventArgs") && // … and EventArgs
// Discard special cases
!m.ParentType.IsDelegate &&
!m.IsGeneratedByCompiler
select new {
m,
m.Visibility,
Debt = 2.ToMinutes().ToDebt(),
Severity = Severity.Medium
}
//<Expl>
// The *{0}* is an event handler. It should be declared as *private*
// or *protected* as it is intended to be used exclusively within its
// own class or class-hierarchy for event handling and should not be
// invoked in other context.
//</Expl>
//<Desc>
// An event handler (like *OnClickButton()*) should be *private* and only
// called on event firing — or *protected*, as some designers (e.g. ASP.NET)
// generate it so sub-classes can call it.
//</Desc>
//<HowToFix>
// If another class needs to call the handler, find a structure matching the
// actual concept: the other class doesn't want to click a button, it wants
// to do what clicking the button also does.
//</HowToFix>
Open in the interactive Rules Explorer · All default rules
Visibility: all 12 items
- Methods that could have a lower visibility ND1800
- Types that could have a lower visibility ND1801
- Fields that could have a lower visibility ND1802
- Types that could be declared as private, nested in a parent type ND1803
- Avoid publicly visible constant fields ND1804
- Fields should be declared as private or protected ND1805
- Constructors of abstract classes should be declared as protected or private ND1806
- Avoid public methods not publicly visible ND1807
- Event handler methods should be declared as private or protected ND1808
- Wrong usage of CannotDecreaseVisibilityAttribute ND1809
- Exception classes should be declared as public ND1810
- Methods that should be declared as 'public' in C#, 'Public' in VB.NET