Редактиране

Споделяне чрез


Tutorial: Create a .NET console application using Visual Studio Code

This tutorial shows how to create and run a .NET console application by using Visual Studio Code.

Prerequisites

Create the app

Create a .NET console app project named "HelloWorld".

  1. Start Visual Studio Code.

  2. Go to the Explorer view and select Create .NET Project. Alternatively, you can bring up the Command Palette using Ctrl+Shift+P (Command+Shift+P on MacOS) and then type ".NET" and find and select the .NET: New Project command.

  3. After selecting the command, you need to choose the project template. Choose Console App.

  4. Select the location where you would like the new project to be created.

  5. Give your new project a name, "HelloWorld".

  6. Select to Show all template options. Set Do not use top-level statements to true. And finally, select Create Project.

  7. In the Do you trust the authors of the files in this folder? dialog, select Yes, I trust the authors. You can trust the authors because this folder only has files generated by .NET and added or modified by you.

  8. Open the Program.cs file to see the simple application created by the template:

    namespace HelloWorld;
    
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
    

    The code defines a class, Program, with a single method, Main, that takes a String array as an argument. Main is the application entry point, the method that's called automatically by the runtime when it launches the application. Any command-line arguments supplied when the application is launched are available in the args array. The code in Main calls the Console.WriteLine(String) method to display a message in the console window.

    C# has a feature named top-level statements that lets you omit the Program class and the Main method. This tutorial doesn't use this feature. Whether you use it in your programs is a matter of style preference. By setting Do not use top-level statements to true when you created the project, you prevented top-level statements from being used.

Run the app

To run your app, select Run > Run without Debugging in the upper menu, or use the keyboard shortcut (Ctrl+F5).

If asked to select a debugger, select C#, then select C#: HelloWorld

The program displays "Hello, World!" and ends.

Enhance the app

Enhance the application to prompt the user for their name and display it along with the date and time.

  1. Open Program.cs.

  2. Replace the contents of the Main method in Program.cs, which is the line that calls Console.WriteLine, with the following code:

    Console.WriteLine("What is your name?");
    var name = Console.ReadLine();
    var currentDate = DateTime.Now;
    Console.WriteLine($"{Environment.NewLine}Hello, {name}, on {currentDate:d} at {currentDate:t}!");
    Console.Write($"{Environment.NewLine}Press Enter to exit...");
    Console.Read();
    

    This code displays a prompt in the console window and waits until the user enters a string followed by the Enter key. It stores this string in a variable named name. It also retrieves the value of the DateTime.Now property, which contains the current local time, and assigns it to a variable named currentDate. And it displays these values in the console window. Finally, it displays a prompt in the console window and calls the Console.ReadKey(Boolean) method to wait for user input.

    NewLine is a platform-independent and language-independent way to represent a line break. It's the same as \n in C#.

    The dollar sign ($) in front of a string lets you put expressions such as variable names in curly braces in the string. The expression value is inserted into the string in place of the expression. This syntax is referred to as interpolated strings.

  3. Save your changes.

    Important

    In Visual Studio Code, you have to explicitly save changes. Unlike Visual Studio, file changes are not automatically saved when you build and run an app.

  4. Select Run>Run without debugging.

  5. Respond to the prompt by entering a name and pressing the Enter key.

    Terminal window with modified program output

  6. Press Enter to exit the program.

Additional resources

Next steps

In this tutorial, you created a .NET console application. In the next tutorial, you debug the app.

This tutorial shows how to create and run a .NET console application by using Visual Studio Code and the .NET CLI. Project tasks, such as creating, compiling, and running a project are done by using the .NET CLI. You can follow this tutorial with a different code editor and run commands in a terminal if you prefer.

Prerequisites

Create the app

Create a .NET console app project named "HelloWorld".

  1. Start Visual Studio Code.

  2. Select File > Open Folder (File > Open... on macOS) from the main menu.

  3. In the Open Folder dialog, create a HelloWorld folder and select it. Then click Select Folder (Open on macOS).

    The folder name becomes the project name and the namespace name by default. You'll add code later in the tutorial that assumes the project namespace is HelloWorld.

  4. In the Do you trust the authors of the files in this folder? dialog, select Yes, I trust the authors. You can trust the authors because this folder only has files generated by .NET and added or modified by you.

  5. Open the Terminal in Visual Studio Code by selecting View > Terminal from the main menu.

    The Terminal opens with the command prompt in the HelloWorld folder.

  6. In the Terminal, enter the following command:

    dotnet new console --framework net7.0
    

    The project template creates a simple application that displays "Hello, World" in the console window by calling the Console.WriteLine(String) method in Program.cs.

    Console.WriteLine("Hello, World!");
    
  7. Replace the contents of Program.cs with the following code:

    namespace HelloWorld
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello, World!");
            }
        }
    }
    

The first time you edit a .cs file, Visual Studio Code prompts you to add the missing assets to build and debug your app. Select Yes, and Visual Studio Code creates a .vscode folder with launch.json and tasks.json files.

Note

If you don't get the prompt, or if you accidentally dismiss it without selecting Yes, do the following steps to create launch.json and tasks.json:

  • Select Run > Add Configuration from the menu.
  • Select .NET 5+ and .NET Core at the Select environment prompt.

The code defines a class, Program, with a single method, Main, that takes a String array as an argument. Main is the application entry point, the method that's called automatically by the runtime when it launches the application. Any command-line arguments supplied when the application is launched are available in the args array.

In the latest version of C#, a new feature named top-level statements lets you omit the Program class and the Main method. Most existing C# programs don't use top-level statements, so this tutorial doesn't use this new feature. But it's available in C# 10, and whether you use it in your programs is a matter of style preference.

Run the app

Run the following command in the Terminal:

dotnet run

The program displays "Hello, World!" and ends.

The dotnet run command

Enhance the app

Enhance the application to prompt the user for their name and display it along with the date and time.

  1. Open Program.cs.

  2. Replace the contents of the Main method in Program.cs, which is the line that calls Console.WriteLine, with the following code:

    Console.WriteLine("What is your name?");
    var name = Console.ReadLine();
    var currentDate = DateTime.Now;
    Console.WriteLine($"{Environment.NewLine}Hello, {name}, on {currentDate:d} at {currentDate:t}!");
    Console.Write($"{Environment.NewLine}Press any key to exit...");
    Console.ReadKey(true);
    

    This code displays a prompt in the console window and waits until the user enters a string followed by the Enter key. It stores this string in a variable named name. It also retrieves the value of the DateTime.Now property, which contains the current local time, and assigns it to a variable named currentDate. And it displays these values in the console window. Finally, it displays a prompt in the console window and calls the Console.ReadKey(Boolean) method to wait for user input.

    NewLine is a platform-independent and language-independent way to represent a line break. Alternatives are \n in C# and vbCrLf in Visual Basic.

    The dollar sign ($) in front of a string lets you put expressions such as variable names in curly braces in the string. The expression value is inserted into the string in place of the expression. This syntax is referred to as interpolated strings.

  3. Save your changes.

    Important

    In Visual Studio Code, you have to explicitly save changes. Unlike Visual Studio, file changes are not automatically saved when you build and run an app.

  4. Run the program again:

    dotnet run
    
  5. Respond to the prompt by entering a name and pressing the Enter key.

    Terminal window with modified program output

  6. Press any key to exit the program.

Additional resources

Next steps

In this tutorial, you created a .NET console application. In the next tutorial, you debug the app.

This tutorial shows how to create and run a .NET console application by using Visual Studio Code and the .NET CLI. Project tasks, such as creating, compiling, and running a project are done by using the .NET CLI. You can follow this tutorial with a different code editor and run commands in a terminal if you prefer.

Prerequisites

Create the app

Create a .NET console app project named "HelloWorld".

  1. Start Visual Studio Code.

  2. Select File > Open Folder (File > Open... on macOS) from the main menu.

  3. In the Open Folder dialog, create a HelloWorld folder and select it. Then click Select Folder (Open on macOS).

    The folder name becomes the project name and the namespace name by default. You'll add code later in the tutorial that assumes the project namespace is HelloWorld.

  4. In the Do you trust the authors of the files in this folder? dialog, select Yes, I trust the authors. You can trust the authors because this folder only has files generated by .NET and added or modified by you.

  5. Open the Terminal in Visual Studio Code by selecting View > Terminal from the main menu.

    The Terminal opens with the command prompt in the HelloWorld folder.

  6. In the Terminal, enter the following command:

    dotnet new console --framework net6.0 --use-program-main
    

    The project template creates a simple application that displays "Hello, World" in the console window by calling the Console.WriteLine(String) method in Program.cs.

    namespace HelloWorld;
    
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
    

    The first time you edit a .cs file, Visual Studio Code prompts you to add the missing assets to build and debug your app. Select Yes, and Visual Studio Code creates a .vscode folder with launch.json and tasks.json files.

    Note

    If you don't get the prompt, or if you accidentally dismiss it without selecting Yes, do the following steps to create launch.json and tasks.json:

    • Select Run > Add Configuration from the menu.
    • Select .NET 5+ and .NET Core at the Select environment prompt.

    The code defines a class, Program, with a single method, Main, that takes a String array as an argument. Main is the application entry point, the method that's called automatically by the runtime when it launches the application. Any command-line arguments supplied when the application is launched are available in the args array.

    In the latest version of C#, a new feature named top-level statements lets you omit the Program class and the Main method. Most existing C# programs don't use top-level statements, so this tutorial doesn't use this new feature. But it's available in C# 10, and whether you use it in your programs is a matter of style preference. In the dotnet new command that you used to create the project, the --use-program-main option prevented top-level statements from being used.

Run the app

Run the following command in the Terminal:

dotnet run

The program displays "Hello, World!" and ends.

The dotnet run command

Enhance the app

Enhance the application to prompt the user for their name and display it along with the date and time.

  1. Open Program.cs.

  2. Replace the contents of the Main method in Program.cs, which is the line that calls Console.WriteLine, with the following code:

    Console.WriteLine("What is your name?");
    var name = Console.ReadLine();
    var currentDate = DateTime.Now;
    Console.WriteLine($"{Environment.NewLine}Hello, {name}, on {currentDate:d} at {currentDate:t}!");
    Console.Write($"{Environment.NewLine}Press any key to exit...");
    Console.ReadKey(true);
    

    This code displays a prompt in the console window and waits until the user enters a string followed by the Enter key. It stores this string in a variable named name. It also retrieves the value of the DateTime.Now property, which contains the current local time, and assigns it to a variable named currentDate. And it displays these values in the console window. Finally, it displays a prompt in the console window and calls the Console.ReadKey(Boolean) method to wait for user input.

    NewLine is a platform-independent and language-independent way to represent a line break. Alternatives are \n in C# and vbCrLf in Visual Basic.

    The dollar sign ($) in front of a string lets you put expressions such as variable names in curly braces in the string. The expression value is inserted into the string in place of the expression. This syntax is referred to as interpolated strings.

  3. Save your changes.

    Important

    In Visual Studio Code, you have to explicitly save changes. Unlike Visual Studio, file changes are not automatically saved when you build and run an app.

  4. Run the program again:

    dotnet run
    
  5. Respond to the prompt by entering a name and pressing the Enter key.

    Terminal window with modified program output

  6. Press any key to exit the program.

Additional resources

Next steps

In this tutorial, you created a .NET console application. In the next tutorial, you debug the app.