Search code examples
c#visual-studioresharpercode-analysisfxcop

How to generate a warning if a specific enum value is used


I am using an enum being exposed by a 3rd party assembly, e.g.,

public enum APIEnum
{
  Val1,
  Val2
}

. However, a number of these values cause incorrect behavior in my application. I want to generate a compiler warning if one of these "bad" enum values is used in code, e.g.,

APIEnum usedVal = APIEnum.Val2;

Compiler Warning: APIEnum.Val2 causes incorrect behavior.

My ultimate goal is to generate a warning that must be consciously #pragma'd if a bad value is used (2% of the overall cases). Otherwise, the warning occurs, and since we have Warnings as Errors, that breaks the compile until fixed or #pragma'd.

I've looked at the threads here and here on using the Obsolete attribute to solve this problem, but I fear the Obsolete will cause confusion since the value is not really obsolete.

I've considered the possibility of using a Resharper code analysis plugin to solve the problem, and that is definitely an option. I'm no expert on Resharper or how to best solve the problem via Resharper.


Solution

  • You can use Structural Search in ReSharper. Go to ReSharper -> Options | Code Inspection -> Custom patterns, click Add Pattern, enter APIEnum.Val2 into the field Search pattern and your error description into Description. Set pattern severity to Show as error. Click Add. That's all. The only downside is if you would have another APIEnum with the same Val2 value in your project, even in the different namespace, then it would also be flagged as error.

    You should also turn on ReSharper -> Options | Code Inspection -> Settings | Analyse errors in whole solution to show errors in every file.