2

I've made a custom attribute that when attached to a method, will cause that method to be called by reflection. However, I'm getting code analysis warnings that indicate the method has no upstream callers (it's private, because I don't want anything else calling it).

Obviously I can suppress that easily enough, but it does clutter the code file. Is there any way to have this warning automatically suppressed for any methods that have this attribute?

For example:

public class ArbitraryClass
{
    [RunOnStartUp]
    private static void RunThisOnStartup()
    {
        // Do some important stuff that can only be done on startup.
    }
}

public static class Program
{
    public static void Main()
    {
        AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(assembly => assembly.GetTypes())
            .SelectMany(type => type.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic))
            .Where(method => method.GetCustomAttribute<RunOnStartupAttribute>() != null)
            .ToList()
            .ForEach(method => method.Invoke(null, new object[0]));

        // Start up the main form etc.
    }
}

(Yes, I know I could probably just use a static initializer in this case, but 'on startup' isn't the only circumstance I use this for).

Flynn1179
  • 11,925
  • 6
  • 38
  • 74

1 Answers1

0

I know this is old, but some people may still see it.

Unfortunately you can't automatically suppress it for all methods with the attribute.

The best you can do is create a global suppression, and target each method, which at least cleans up the clutter.

Simply create a file named "GlobalSuppressions.cs", use the System.Diagnostics.CodeAnalysis namespace, and add suppress the warning for your method like below. Should also note that it doesn't have to exist in GlobalSupressions.cs, it can exist in any class, as long as its before the namespace.

using System.Diagnostics.CodeAnalysis;


[assembly: SuppressMessage("Category", "CA1811", Scope = "member", Target = "~M:ArbitraryClass.RunThisOnStartup")]

This can also be created automatically by pressing "Ctrl" + ".", then select "Suppress or Configure Issues," "Supress (Warning ID)," and finally "in Suppression File." I assume this feature did not exist 5 years ago, as the original poster knew about suppressing warnings.

Addio
  • 89
  • 1
  • 6
  • I knew about it, but this is kind of the polar opposite of what I hoped to achieve. For one thing, it might not be my own code- I was thinking of including an attribute in a library for anyone to use, and hoped to have analysis warnings that used it suppressed automatically; requiring the addition of specific suppressions defeats the purpose of my question. This is still useful info or many situations though, but not mine unfortunately. – Flynn1179 Feb 18 '21 at 11:17