Share via


Do not declare protected members in sealed types

TypeName

DoNotDeclareProtectedMembersInSealedTypes

CheckId

CA1047

Category

Microsoft.Design

Breaking Change

NonBreaking

Cause

A public type is sealed (NotInheritable in Visual basic) and declares a protected member. This rule does not report violations for Finalize methods, which must follow this pattern.

Rule Description

Types declare protected members so that inheriting types can access or override the member. By definition, you cannot inherit from a sealed type, which means that protected methods on sealed types cannot be called.

The C# compiler issues a warning for this error.

How to Fix Violations

To fix a violation of this rule, change the access level of the member to private, or make the type inheritable.

When to Exclude Warnings

Do not exclude a warning from this rule. Leaving the type in its current state can cause maintenance issues and does not provide any benefits.

Example

The following example shows a type that violates this rule.

Imports System

Namespace DesignLibrary

   Public NotInheritable Class BadSealedType
      Protected  Sub MyMethod
      End Sub
   End Class

End Namespace
using System;

namespace DesignLibrary
{
   public sealed class SealedClass
   {
      protected void ProtectedMethod(){}
   }
}

The following example shows a type that violates this rule.

The above sealed type declares a protected member, which cannot be called from outside the class that declares it.

If the method was designed to be called by other types, increase its accessibility to public, otherwise, reduce its accessibility to private.

The following example fixes the above violation by increasing the method's accessibility to public.