Reputation: 341
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?
Upvotes: 4
Views: 7537
Reputation: 2112
You want to enable "Top-Level Statements" during your project creation. It is a checkbox that you must check when you first create you project/solution.
Upvotes: 0
Reputation: 172230
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):
using System;
Console.WriteLine("I got " + args.Length + " command line arguments.");
This is documented here:
You don't declare an
args
variable. For the single source file that contains your top-level statements, the compiler recognizesargs
to mean the command-line arguments. The type ofargs
is astring[]
, as in all C# programs.
For completeness: If you want a "classic" Main
entry point, you need
Main
withvoid
or int
(or Task
/Task<int>
, if you create an async
method) andstring[]
parameter.It seems like you miss the class in your example. A full minimal working example looks like this:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
}
}
The exact criteria are documented here:
Upvotes: 10
Reputation: 54417
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:
Whether to generate an explicit Program class and Main method instead of top-level statements.
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.
Upvotes: 1