Share via


CA2146: Types must be at least as critical as their base types and interfaces

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
RuleId CA2146
Category Microsoft.Security
Breaking change Breaking

Cause

A transparent type is derived from a type that is marked with the SecuritySafeCriticalAttribute or the SecurityCriticalAttribute, or a type that is marked with the SecuritySafeCriticalAttribute attribute is derived from a type that is marked with the SecurityCriticalAttribute attribute.

Note

This rule has been deprecated. For more information, see Deprecated rules.

Rule description

This rule fires when a derived type has a security transparency attribute that is not as critical as its base type or implemented interface. Only critical types can derive from critical base types or implement critical interfaces, and only critical or safe-critical types can derive from safe-critical base types or implement safe-critical interfaces. Violations of this rule in level 2 transparency result in a TypeLoadException for the derived type.

How to fix violations

To fix this violation, mark the derived or implementing type with a transparency attribute that is at least as critical as the base type or interface.

When to suppress warnings

Do not suppress a warning from this rule.

Example

using System;
using System.Security;

namespace TransparencyWarningsDemo
{

    [SecuritySafeCritical]
    public class SafeCriticalBase
    {
    }

    // CA2156 violation - a transparent type cannot derive from a safe critical type.  The fix is any of:
    //   1. Make SafeCriticalBase transparent
    //   2. Make TransparentFromSafeCritical safe critical
    //   3. Make TransparentFromSafeCritical critical
    public class TransparentFromSafeCritical : SafeCriticalBase
    {
    }

    [SecurityCritical]
    public class CriticalBase
    {
    }

    // CA2156 violation - a transparent type cannot derive from a critical type.  The fix is any of:
    //   1. Make CriticalBase transparent
    //   2. Make TransparentFromCritical critical
    public class TransparentFromCritical : CriticalBase
    {
    }

    // CA2156 violation - a safe critical type cannot derive from a critical type.  The fix is any of:
    //   1. Make CriticalBase transparent
    //   2. Make CriticalBase safe critical
    //   3. Make SafeCriticalFromCritical critical
    [SecuritySafeCritical]
    public class SafeCriticalFromCritical : CriticalBase
    {
    }

}