Search code examples
c#filetoplevel-statement

How do I fix the top-level statement's error?


Program1.cs Regular C# file, works perfectly.

Random numberGen = new Random();

int roll1 = 1;
int roll2 = 0;
int roll3 = 0;
int roll4 = 0;

int attempts = 0;

Console.WriteLine("Press enter to roll the dies");

while (roll1 != roll2 || roll2 != roll3 || roll3 != roll4 || roll4 != roll1)
{
    Console.ReadKey();

    roll1 = numberGen.Next(1, 7);
    roll2 = numberGen.Next(1, 7);
    roll3 = numberGen.Next(1, 7);
    roll4 = numberGen.Next(1, 7);
    Console.WriteLine("Dice 1: " + roll1 + "\nDice 2: " + roll2 + "\nDice 3: " + roll3 + "\nDice 4: " + roll4 + "\n");
    attempts++;
}

Console.WriteLine("It took " + attempts + " attempts to roll a four of a kind.");

Console.ReadKey();

Program2.cs

Console.ReadKey();

Under the module Console it pops up an error: Only one compilation unit can have top-level statements. Error: CS8802

I tried in the terminal dotnet new console --force, but it just ended up deleting my program.

I want to run multiple C# files in the same folder without getting the Only one compilation unit can have top-level statements or other similar errors.


Solution

  • In dotnet 6 and newer, it is possible to use a top-level statement, which means you do not need to have a class name for the main method.

    So when you have 2 cs file that does not have class and namespace, the compiler thinks you have 2 main methods.

    So you can eventually do something like for Program1.cs:

    namespace ConsoleApp1;
    
    class Program1
    {
        public static void GetRolling()
        {
            Random numberGen = new Random();
    
            int roll1 = 1;
            int roll2 = 0;
            int roll3 = 0;
            int roll4 = 0;
    
            int attempts = 0;
    
            Console.WriteLine("Press enter to roll the dies");
    
            while (roll1 != roll2 || roll2 != roll3 || roll3 != roll4 || roll4 != roll1)
            {
                Console.ReadKey();
    
                roll1 = numberGen.Next(1, 7);
                roll2 = numberGen.Next(1, 7);
                roll3 = numberGen.Next(1, 7);
                roll4 = numberGen.Next(1, 7);
                Console.WriteLine("Dice 1: " + roll1 + "\nDice 2: " + roll2 + "\nDice 3: " + roll3 + "\nDice 4: " + roll4 + "\n");
                attempts++;
            }
    
            Console.WriteLine("It took " + attempts + " attempts to roll a four of a kind.");
        }
    }
    

    and for Program2.cs something like:

    namespace ConsoleApp1;
    
    public class Program2
    {
        public static void Main(string[] args)
        {
            Program1.GetRolling();
            Console.ReadKey();
        }
    }
    

    Otherwise, it is like saying you have a twice (2x) public static void Main(string[] args) and that is not possible. Therefore you get that Error.