I have a c# console application where I need to take some command line arguments.
For this reason I need a main method, instead of the non-main method that is currently there, and since I can’t find any material on how to do it without.
So, I tried just pasting some code into my newly created visual studio dotnet 6 c# application:
static void Main(string[] args)
{
Console.WriteLine("hi there");
}
Which does’nt work. The code is not executed.
How do I add a main method, so I can take some cmd arguments?
2
Answers
When you create the project, there is a box to check to not use top-level statements. Create a new project and check that box, then it will work just like in older versions. The box even has an info icon next to it that, when moused-over displays this message:
If you do create a project with top-level statements, this URL is provided at the top of the code file. The information you needed was provided but you didn’t pay attention. It’s always important to pay attention to what VS is trying to tell you because it provides a lot of useful information.
You don’t need a classic Main method to access command-line arguments. You can just access the "magic" variable
args
. The following is a complete and valid C# program (fiddle):This is documented here:
For completeness: If you want a "classic"
Main
entry point, you needMain
withvoid
orint
(orTask
/Task<int>
, if you create anasync
method) andstring[]
parameter.It seems like you miss the class in your example. A full minimal working example looks like this:
The exact criteria are documented here: