Home > Enterprise >  How do I add code outside the scope of Main when using c# 9 Top Level Statements?
How do I add code outside the scope of Main when using c# 9 Top Level Statements?

Time:12-23

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?

CodePudding user response:

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.

  • Related