Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

c#-9.0

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?

like image 625
Guil75 Avatar asked Dec 27 '25 16:12

Guil75


1 Answers

I don't think the currently-accepted 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

like image 188
dongus Avatar answered Dec 30 '25 06:12

dongus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!