Home > database >  Attributes on C#9 top level statements file
Attributes on C#9 top level statements file

Time:11-15

I'm trying to add attributes to a top-level statements file, and I'm not finding anything about it. Is it possible?

For some context: I want to disable a rule only in that file with:

[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1516:ElementsMustBeSeparatedByBlankLine", Justification = "Reviewed.")]

It's a rule with a known bug in top-level statements.

Is there any way?

CodePudding user response:

Assuming you want to set an assembly-wide attribute, then it's the same as it was before C# 9.0. You're missing the assembly: keyword.

https://docs.microsoft.com/en-us/dotnet/standard/assembly/set-attributes

Change your code to add the assembly: keyword, like so:

[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1516:ElementsMustBeSeparatedByBlankLine", Justification = "Reviewed.")

If you want to add the attribute to the implicit entrypoint method (aka Program.Main) or its parent type class Program then you cannot, simply because C# 9.0's top-level-statements design does not allow programs to name or reference the method at all.

This is mentioned, briefly, in the documentation on top-level methods (emphasis mine):

https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements#implicit-entry-point-method

Implicit entry point method

The compiler generates a method to serve as the program entry point for a project with top-level statements. The name of this method isn't actually Main, it's an implementation detail that your code can't reference directly. The signature of the method depends on whether the top-level statements contain the await keyword or the return statement.

...in which case you'll need to change your code back to using a traditional explicit Main method:

[SuppressMessage("SomeClassRule", "", Justification = "It's my computer")]
public static class Program
{
    [SuppressMessage("SomeMethodRule", "", Justification = "It's my computer")]
    public static async Task<Int32> Main( String[] args )
    {
        return 0;
    }
}
  • Related