Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid 'Method is never used' message?

In the following example, Resharper complains about DoA() method never being used, despite being implemented by the 'AImplementator' class:

namespace Test
{
    public interface A
    {
        // Method 'DoA' is never used
        void DoA();
    }

    public class AImplementator: A
    {
        public void DoA()
        {
            throw new System.NotImplementedException();
        }
    }
}

I can't understand this behavior, since the interface IS being used.

  1. Why this happens?
  2. How can I fix this warning?

Obs: I can supress the warning using comments or the [UsedImplicitly] attribute. But neither of these options seems to be correct given the situation. I'm using Resharper 9.1.

like image 678
Genos Avatar asked Aug 21 '26 12:08

Genos


2 Answers

This warning will only be displayed when the Solution-Wide Analysis is enabled.

The warning is about the usage (in this case e.g. a call) of the interface method. The following example should demonstrate it (note the var vs. interface as local variable type).

var instance = new AImplementator();
// Does NOT make A.DoA() "used":
instance.DoA();

A instanceAsInterface = new AImplementator();
// DOES make A.DoA() "used":
instanceAsInterface.DoA();
like image 61
ulrichb Avatar answered Aug 23 '26 01:08

ulrichb


To answer other people going here.

If you do have resharper 10.

you can use jetrains annotatoins:

  • nuget it into your project: https://www.nuget.org/packages/JetBrains.Annotations
  • docs: https://www.jetbrains.com/help/resharper/10.0/Reference__Code_Annotation_Attributes.html

putting the attribute: [UsedImplicitly] above the class will suffice.

What is great to know is that it also works putting it on the base class.

In this case Putting it on interface A will fix the message showing up for all subclasses (great for ioc implementations)

namespace Test
{
    [JetBrains.Annotations.UsedImplicitly]
    public interface A
    {
        // Method 'DoA' is never used
        void DoA();
    }

    public class AImplementator: A
    {
        public void DoA()
        {
            throw new System.NotImplementedException();
        }
    }
}

Tests

Best solution would be to write unit tests to cover these functions. The advantage would be that also your specs are covered.

like image 35
Joel Harkes Avatar answered Aug 23 '26 02:08

Joel Harkes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!