Search code examples
c#reflectionattributessuppressmessage

Can't access SuppressMessage attribute at runtime


I am trying to create a unit test that will only fail for types which don't suppress the corresponding message. However, I am unable to access the SuppressMessage attributes on any of my types in my unit tests. Is it possible to access SuppressMessage attributes at runtime? I've included a simplified version of my unit test.

[System.Diagnostics.CodeAnalysis.SuppressMessage("Foo", "Bar")]
public interface IMyInterface { }

public void UnitTest()
{
    var getCustomAttributes = typeof(IMyInterface).GetCustomAttributes();   //Returns an empty array
    //Skip check if message should be suppressed
}

Solution

  • Build your assembly (in which the IMyInterface is defined) with conditional symbol CODE_ANALYSIS

    [Conditional("CODE_ANALYSIS")]
    [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
    public sealed class SuppressMessageAttribute : Attribute {