Get Started with .NET Console Applications
Welcome to the world of .NET development! This guide will walk you through creating your first .NET console application, a fundamental building block for many powerful applications.
Prerequisites
Before you begin, ensure you have the .NET SDK installed. You can download it from the official .NET website.
Step 1: Create a New Console Application
Open your terminal or command prompt and navigate to the directory where you want to create your project. Then, run the following command:
This command creates a new directory named MyConsoleApp
and generates a basic console application project structure inside it.
Step 2: Navigate to Your Project Directory
Change your current directory to the newly created project folder:
Step 3: Explore the Project Files
Inside the MyConsoleApp
directory, you'll find several files:
MyConsoleApp.csproj
: The project file that contains project-specific configuration and metadata.Program.cs
: The main entry point for your application. This is where you'll write your code.obj
directory: Contains intermediate build files.bin
directory: Contains the compiled output of your application.
Step 4: Write Your First Code
Open the Program.cs
file in your favorite text editor or IDE. You'll see some starter code:
using System;
// Namespace declaration
namespace MyConsoleApp
{
// Main class
class Program
{
// Entry point of the application
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
This code simply prints "Hello, World!" to the console. Let's modify it to do something more interesting:
using System;
namespace MyConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to .NET Console Apps!");
Console.Write("Please enter your name: ");
string? name = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(name))
{
Console.WriteLine($"Hello, {name}! Nice to meet you.");
}
else
{
Console.WriteLine("Hello, anonymous user!");
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey(); // Keeps the console window open until a key is pressed
}
}
}
Step 5: Run Your Application
Save the changes to Program.cs
. Now, run your application from the terminal using the following command:
You should see the output in your terminal, prompting you to enter your name. After you enter your name and press Enter, it will greet you.
dotnet run
command compiles and executes your application. It's a convenient way to test your code during development.
Next Steps
Congratulations! You've created and run your first .NET console application. From here, you can explore more advanced topics such as:
- Working with variables and data types
- Control flow statements (if/else, loops)
- Object-Oriented Programming (classes, objects)
- File I/O operations
- Error handling and exception management
Refer to the rest of the MSDN .NET Documentation for comprehensive details and further learning resources.