Home > Software design >  How do I add a working Main method to a dotnet 6 console application to access command line argument
How do I add a working Main method to a dotnet 6 console application to access command line argument

Time:10-19

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?

CodePudding user response:

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 recognizes args to mean the command-line arguments. The type of args is a string[], as in all C# programs.


For completeness: If you want a "classic" Main entry point, you need

  • a class or struct with
  • a static method called Main with
  • a return type of either void or int (or Task/Task<int>, if you create an async method) and
  • no parameter or a single string[] 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:

CodePudding user response:

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.

  • Related