Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect unnecessary unsafe keyword usage in methods and classes #7518

Open
am11 opened this issue Dec 26, 2024 · 0 comments
Open

Detect unnecessary unsafe keyword usage in methods and classes #7518

am11 opened this issue Dec 26, 2024 · 0 comments

Comments

@am11
Copy link
Member

am11 commented Dec 26, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant