Skip to content

Detect unnecessary unsafe keyword usage in methods and classes #7518

@am11

Description

@am11

Describe the problem you are trying to solve

Unnecessary usage of the unsafe keyword on classes or methods can lead to misleading code, as it implies the use of unsafe operations (e.g., pointers or fixed size buffers) even when none are present. This reduces code clarity and may result in unwarranted caution when working with the code.

Describe suggestions on how to achieve the rule

Develop an analyzer that flags methods or classes marked with the unsafe keyword when no unsafe operations are detected. Unsafe operations include:

  • Pointer manipulation
  • Fixed size buffers
  • Any other operations explicitly requiring unsafe context.

The associated code-fix could remove the redundant unsafe keyword, or scope it appropriately to only methods that require it.

Additional context

Example 1:

Input:

unsafe class Example
{
    public void SafeMethod() { }
}

Output (after code fix):

class Example
{
    public void SafeMethod() { }
}

Example 2:

Input:

unsafe class Example
{
    public void SafeMethod() { }
    public unsafe void UnsafeMethod()
    {
        int* ptr = null;
    }
}

Output (after code fix):

class Example
{
    public void SafeMethod() { }
    public unsafe void UnsafeMethod()
    {
        int* ptr = null;
    }
}

Related dotnet/runtime#94941 - @EgorBo is cleaning up the code in dotnet/runtime#110953 (and other similar PRs) and I think a built-in analyzer would help protect the repo state from regressing.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions