'How do I add code outside the scope of Main when using C# 9 Top Level Statements?

My understanding is that it is similar to write code directly into the old "static void Main(string[] args)" without the need to display what's above.

However, I used to declare my variables in the class Program to have them accessible from other classes (apologies if not best practice, I learnt C# by myself and as long as it works, I'm happy with my code). See example below:

using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;

namespace myNameSpace
{
    class Program
    {
        //variables declaration
        public static string abc = "abc";
        public static int xyz = 1;

        static void Main(string[] args)
        {
            //code goes here
        }
    }
}

With C# 9, it seems I can only declare variables in the Main section, so how can I declare them to be able to access them from other classes?



Solution 1:[1]

When you use the Top-Level Program feature of C# 9, you give up the ability to put anything outside the Main method scope. Fields, properties, attributes on the Main method or Program class, setting the namespace, etc are all no longer available (the only exception is "importing" namespaces with using lines).

If that limitation doesn't work for you, don't use the feature.

Solution 2:[2]

I don't think the answer is correct, if you toss a partial class signature in Program.cs you can most certainly add things like static-scoped fields and attributes:

var customAttributes = (CustomAttribute[])typeof(Program).GetCustomAttributes(typeof(CustomAttribute), true);
Console.WriteLine(customAttributes[0].SomePropery);
Console.WriteLine(MyField);


[Custom(SomePropery = "hello world")]
public partial class Program
{ 
    private const string MyField = "value";
}

class CustomAttribute : Attribute
{
    public string SomePropery { get; set; }
}

The above code and nothing else in Program.cs will output:

/home/dongus/bazinga/bin/Debug/net6.0/bazinga
hello world
value

Process finished with exit code 0.

I use this method to apply the [ExcludeFromCodeCoverage] attribute to my projects' Program.cs files

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 dongus