Resharper C# incorrectly claims method as unused

Answered

In this code reshaper claims MyMethod is unused. 

class Program
{
    public static void MyMethod() => System.Console.WriteLine("Got called!");
    static void Main()
    {
        typeof(Program).GetMethod("MyMethod")?.Invoke(null, null);
        System.Console.ReadKey();
    }
}
How to turn it of?

0
1 comment

Hello Arno,

ReSharper is detecting MyMethod() as an unused method because it appears as if it is never directly called from any other method in your code. However, in this case, you are obtaining the method through reflection and invoking it in the Main method, which is a less typical use case and not automatically detected by ReSharper.
To tell ReSharper that this method is actually used and suppress the warning, you can add the [UsedImplicitly] attribute from the JetBrains.Annotations namespace. Here's how you can do it:
First, ensure that the JetBrains.Annotations NuGet package is installed in your project. If it is not already installed, you can easily add it:

1. Right-click your project in the Solution Explorer.
2. Click "Manage NuGet Packages".
3. Click on "Browse" and search for "JetBrains.Annotations".
4. Click on the package in the search results and click "Install".

Then, modify your code to include the [UsedImplicitly] attribute:


using JetBrains.Annotations;

class Program
{
[UsedImplicitly]
public static void MyMethod() => System.Console.WriteLine("Got called!");

static void Main()
{
typeof(Program).GetMethod("MyMethod")?.Invoke(null, null);
System.Console.ReadKey();
}
}


By adding this attribute, ReSharper will understand that the method is used implicitly and not raise any warning for it.

1

Please sign in to leave a comment.