❔ top-level statement
I have a folder where I have 1 cs file and it is working perfect. I want to start working on a new CS file within the same folder and when I try to compile, then it says " Only one compilation unit can have top-level statements". How can I solve this issue?
21 Replies
You need to write classes etc
Top-level statements - C# tutorial
This tutorial shows how you can use top-level statements to experiment and prove concepts while exploring your ideas
You generally cannot just write code that 'does stuff' outside of a method, outside of a class.
The one file allowed for top level statements is an exception
The one file allowed for top level statements is an exception
ok, I need to make method and class?
Yes, essentially you can only have one file that doesn't contain the class and method declarations
the console output says vthat I am missing partial modifier on declaration of type 'program'
i have tried to make an file with method and class (help from ChatGPT), but it doesnt work
can we have an online session?
but this is the top-level statement file
Yes, does that mean you have another file?
yes
what's in that file?
i have 2 cs files
this is my main file
When you have a file that removes the top level statements, that file is assumed to be
class Program
with a static void Main
, so you shouldn't be use that class name in your file that does have top level statements. Also, if these files are completely disconnected then you should probably put them in different ProjectsSo I need to make a folder everytime I want to a new cs file?
No, just don't have a file without top level statements, and then create another file with a
class Program
in it as well, as these will conflict
Moving them into separate projects was just a suggestion based on them seeming to be completely unrelated functionality
essentially the Main
method in your Program
class is the entry point for your application, i.e. where the code will start executing from, so you can only have one of these, at this point in time it might be easier to NOT exclude top level statements as it can lead to confusionso I should include top level-statement
You don't have to, I just think it helps to avoid confusion when you're starting out
i understand
If you just want to create one file scripts then i can recommend https://github.com/dotnet-script/dotnet-script
GitHub
GitHub - dotnet-script/dotnet-script: Run C# scripts from the .NET ...
Run C# scripts from the .NET CLI. Contribute to dotnet-script/dotnet-script development by creating an account on GitHub.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.