Edit

Share via


Remove unnecessary unsafe modifier (IDE0380)

Property Value
Rule ID IDE0380
Title Remove unnecessary unsafe modifier
Category Style
Subcategory Unnecessary code rules (modifier preferences)
Applicable languages C#
Options None

Overview

This rule identifies code blocks, methods, types, or other declarations marked with the unsafe modifier that don't actually contain any unsafe operations. The unsafe modifier allows the use of pointers and other unsafe code features, but when those features aren't being used, the modifier is unnecessary and should be removed for code clarity.

Example

// Code with violations.

// Unnecessary, no unsafe operations.
unsafe class MyClass
{
    public void Method()
    {
        var x = 5;
    }
}

// Unnecessary, no unsafe operations.
unsafe void ProcessData(int value)
{
    Console.WriteLine(value);
}

// Fixed code.
class MyClass
{
    public void Method()
    {
        var x = 5;
    }
}

void ProcessData(int value)
{
    Console.WriteLine(value);
}

// Example where 'unsafe' is needed.
unsafe class ValidUsage
{
    int* pointer; // Pointer type requires 'unsafe'.
}

Suppress a warning

If you want to suppress only a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable IDE0380
// The code that's violating the rule is on this line.
#pragma warning restore IDE0380

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.IDE0380.severity = none

To disable all of the code-style rules, set the severity for the category Style to none in the configuration file.

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none

For more information, see How to suppress code analysis warnings.

See also