CA1052: Static holder types should be sealed

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at CA1052: Static holder types should be sealed.

TypeName|StaticHolderTypesShouldBeSealed|
|CheckId|CA1052|
|Category|Microsoft.Design|
|Breaking Change|Breaking|

A public or protected type contains only static members and is not declared with the sealed (NotInheritable) modifier.

This rule assumes that a type that contains only static members is not designed to be inherited, because the type does not provide any functionality that can be overridden in a derived type. A type that is not meant to be inherited should be marked with the sealed modifier to prohibit its use as a base type.

To fix a violation of this rule, mark the type as sealed. If you are targeting .NET Framework 2.0 or earlier, a better approach is to mark the type as static. In this manner, you avoid having to declare a private constructor to prevent the class from being created.

Suppress a warning from this rule only if the type is designed to be inherited. The absence of the sealed modifier suggests that the type is useful as a base type.

Description

The following example shows a type that violates the rule.

Code

using namespace System;

namespace DesignLibrary
{
    public ref class StaticMembers
    {
        static int someField;

        StaticMembers() {}

    public:
        static property int SomeProperty
        {
            int get()
            {
                return someField;
            }

            void set(int value)
            {
                someField = value;
            }
        }

        static void SomeMethod() {}
    };
}

Description

The following example shows how to fix a violation of this rule by marking the type with the static modifier.

Code

using System; 

namespace DesignLibrary
{    
    public static class StaticMembers    
    {        
        private static int someField;     
            
        public static int SomeProperty        
        {            
            get { return someField; }            
            set { someField = value; }        
        }                
        
        public static void SomeMethod()         
        {        
        }         
        
        public static event SomeDelegate SomeEvent;    
    }     
    
    public delegate void SomeDelegate();
}

CA1053: Static holder types should not have constructors

Show: