How to avoid 'Method is never used' message?

2.4k views Asked by At

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.

2

There are 2 answers

0
ulrichb On BEST ANSWER

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();
2
Joel Harkes On

To answer other people going here.

If you do have resharper 10.

you can use jetrains annotatoins:

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.