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 ends 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.
CodePudding user response:
In dotnet 6, you do not need to have a class name for the main method.
So when you have 2 class that does not have class and namespace, the compiler thinks you have 2 main methods.
So you do something like
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 some think like:
namespace ConsoleApp1;
public class Program2
{
public static void Main(string[] args)
{
Program1.GetRolling();
Console.ReadKey();
}
}
Otherwise, it is like saying have 2x public static void Main(string[] args)
and that is not possible.