Home > OS >  C# Variables declaration in c#9 [edited from .NET 6.0]
C# Variables declaration in c#9 [edited from .NET 6.0]

Time:12-23

[edited]With c# 9, the header is now changed from previous version, I'm referring to "Top Level Program feature".

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? FYI, I would access them the way shown below

    using System.IO;
    using System.Net;
    using System.Diagnostics;

    namespace myOtherNameSpace
    {

        public class accessVariable
        {
            public static void printVar_abc()
            {
                Console.WriteLine(myNameSpace.Program.abc);
            }
        }
    }

Please feel free to suggest better practice as I'm keen to improve my coding.

Thanks!

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, 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