404 Not Found

404 Not Found


nginx

Setting Up the Development Environment

Setting up a development environment is like preparing an art studio — once the canvas (.NET SDK) and brushes (VS Code) are in place, you can start creating (writing C# code).

Installing the .NET SDK

The .NET SDK (Software Development Kit) is the core toolkit for developing C# programs, containing the compiler, runtime, and project management tools. You need to install it first before you can write, compile, and run C# programs.

Installing on Windows

  1. Visit https://dotnet.microsoft.com/download/dotnet/8.0 to download the .NET 8 SDK installer
  2. Run the installer and complete the installation with the default options
  3. Open a command prompt and verify:
BASH
dotnet --version
TEXT
8.0.xxx

If you see a version number, the installation was successful.

Installing on macOS

Install via Homebrew:

BASH
brew install dotnet-sdk

Or download the macOS installer from the official website. Verify the same way:

BASH
dotnet --version

Installing on Linux

Ubuntu/Debian:

BASH
sudo apt-get update
sudo apt-get install -y dotnet-sdk-8.0

CentOS/RHEL:

BASH
sudo dnf install -y dotnet-sdk-8.0

Verify the installation:

BASH
dotnet --version

💡 Tip: This book uses .NET 8 (LTS — Long-Term Support). Make sure to install the SDK, not just the Runtime. The SDK includes all the tools needed for development.

Key Components Included in the SDK

Component Role
Roslyn Compiler Compiles C# code into Intermediate Language (IL)
dotnet CLI Command-line tool for creating, building, and running projects
.NET Runtime Executes compiled programs
NuGet Package Manager Manages third-party library dependencies

Configuring VS Code

VS Code is a free code editor developed by Microsoft. Paired with the C# extension, it provides a powerful C# development experience.

Installing VS Code

Go to https://code.visualstudio.com to download and install.

Installing Required Extensions

Open VS Code, press Ctrl+Shift+X to open the Extensions marketplace, then search for and install:

Extension Purpose
C# Dev Kit (Microsoft) All-in-one support for syntax highlighting, IntelliSense, debugging, and project management
C# (Microsoft) Basic C# language service (usually installed automatically with Dev Kit)

Configuring C# Dev Kit

After installing C# Dev Kit, the extension automatically detects your installed .NET SDK. You can confirm the configuration is correct by:

  1. Press Ctrl+Shift+P, type .NET: New Project — if a project template list appears, the setup is successful
  2. The bottom status bar should display the .NET SDK version number

⚠️ Warning: When opening a folder in VS Code, create a dedicated folder (e.g., csharp-learn) and open the entire folder in VS Code rather than a single file. This is required for C# Dev Kit to work properly.

Your First Program: Hello World

Example

Use the dotnet CLI to create your first console application:

BASH
dotnet new console -n MyFirstApp
▶ Try it Yourself
TEXT
The template "Console App" was created successfully.
Processing post-creation actions...
Restoring packages...
Determining projects to restore...
Restored MyFirstApp.csproj (in 1.2s).

Navigate into the project directory and run it:

BASH
cd MyFirstApp
dotnet run
TEXT
Hello, World!

That's your first C# program! The dotnet new console command automatically generates the project structure and code.

Project Structure

After creation, the project folder contains:

TEXT
MyFirstApp/
├── MyFirstApp.csproj
├── Program.cs
└── obj/
    └── ...
File Purpose
Program.cs Program entry point, contains the main code
MyFirstApp.csproj Project configuration file, defines SDK, target framework, etc.
obj/ Intermediate build output directory

Common dotnet CLI Commands

The dotnet CLI is the core command-line tool for .NET development. Mastering it is more efficient than relying on an IDE.

Project Management Commands

Command Purpose Example
dotnet new console Create a console project dotnet new console -n MyApp
dotnet new classlib Create a class library project dotnet new classlib -n MyLib
dotnet new list List all available templates dotnet new list

The -n parameter specifies the project name. If omitted, the current folder name is used.

Build, Run, and Publish

Command Purpose Example
dotnet build Compile the project (without running) dotnet build
dotnet run Compile and run the project dotnet run
dotnet publish Publish the project (for deployment) dotnet publish -c Release

Example

BASH
dotnet build
▶ Try it Yourself
TEXT
MSBuild version 17.8.xxxx
  Determining projects to restore...
  Restored MyFirstApp.csproj (in 102 ms).
  MyFirstApp -> G:\csharp-learn\MyFirstApp\bin\Debug\net8.0\MyFirstApp.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

🔥 Tip: dotnet run = dotnet build + automatic execution. Use dotnet run for quick testing during development, and dotnet build to check for compilation issues in formal builds.

Top-Level Statements vs. Traditional Program.Main

C# 9 introduced top-level statements, dramatically simplifying console program syntax. Understanding both styles helps you read C# code from different eras.

Top-Level Statements (C# 9+, the Default)

dotnet new console generates a Program.cs that uses top-level statements by default:

CSHARP
System.Console.WriteLine("Hello, World!");

Just one line — no namespace, no class, no Main method. The compiler automatically wraps it in a generated Main method.

Traditional Program.Main Style

The pre-C# 9 approach, where all code must go inside a Main method:

CSHARP
using System;

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

Comparing the Two Styles

Feature Top-Level Statements Traditional Program.Main
Code volume Very little More boilerplate
Entry method Auto-generated by compiler Manually defined static void Main
using declarations Can be omitted (use fully qualified names) Usually need using System;
Namespace No declaration needed Must declare
Command-line arguments Access via args variable directly Via Main(string[] args) parameter
Use cases Simple programs, learning, scripting Large projects needing fine-grained entry control
C# version C# 9+ All versions

📌 Key Point: Top-level statements and the traditional style are functionally equivalent. Top-level statements are just syntactic sugar — the generated IL code is essentially the same. Only one file in a project can use top-level statements.

Accessing Command-Line Arguments with Top-Level Statements

CSHARP
if (args.Length > 0)
{
    System.Console.WriteLine($"Hello, {args[0]}!");
}
else
{
    System.Console.WriteLine("Hello, World!");
}
BASH
dotnet run -- Alice
TEXT
Hello, Alice!

Arguments after -- are passed to the program. In top-level statements, args is automatically injected by the compiler.

Common Compiler Errors

As a beginner, you will definitely encounter compiler errors. Don't panic — learning to read error messages is more important than avoiding them.

CS1002: Semicolon Expected

CSHARP
System.Console.WriteLine("Hello, World!")
TEXT
Program.cs(1,40): error CS1002: ; expected

The error format is filename(line,column): error code: description. This line is missing a semicolon at the end — every C# statement must end with a semicolon.

CS0103: Name Does Not Exist in the Current Context

CSHARP
Console.WriteLine("Hello, World!");
TEXT
Program.cs(1,1): error CS0103: The name 'Console' does not exist in the current context

You used Console without using System; or the fully qualified name System.Console. Two solutions: add using System; or use System.Console.

CS0117: Does Not Contain a Definition

CSHARP
System.Console.WritLine("Hello, World!");
TEXT
Program.cs(1,17): error CS0117: 'Console' does not contain a definition for 'WritLine'

WriteLine was misspelled as WritLine. The compiler is telling you that the Console class has no member called WritLine — check your spelling.

CS0120: Object Reference Required for Non-Static Field

CSHARP
namespace MyApp
{
    class Program
    {
        string name = "C#";
        static void Main(string[] args)
        {
            System.Console.WriteLine(name);
        }
    }
}
TEXT
Program.cs(8,37): error CS0120: An object reference is required for the non-static field, method, or property 'Program.name'

You accessed a non-static field name from the static method Main. Static methods belong to the class itself, while non-static members belong to instances of the class — you need to create an object first.

⚠️ Tip for reading error messages: The reported line number may point to the position after the actual mistake. If a line shows an error, check that line and the one above it for spelling, semicolons, and brackets. CS codes are official Microsoft error codes — you can search for a CS number online to find detailed explanations.

❓ FAQ

Q After installing the .NET SDK, the command line says "dotnet is not recognized as a command." What should I do?
A This means the .NET installation directory is not in your system PATH. On Windows, re-running the SDK installer usually fixes this automatically. If not, manually add the dotnet directory (e.g., C:\Program Files\dotnet) to your system PATH, then restart the command line.
Q What's the difference between C# Dev Kit and the old C# extension?
A C# Dev Kit is a new extension released by Microsoft in 2023. It integrates project management, a Solution Explorer, a Test Explorer, and more — the experience is much closer to Visual Studio. The old C# extension only provides basic language services. C# Dev Kit is recommended.
Q Is there a performance difference between top-level statements and the traditional style?
A None at all. Top-level statements are just syntactic sugar — the compiler converts them into a standard Main method. The generated IL code and runtime performance are identical. Choose whichever style suits your code readability and project scale.
Q What's the difference between dotnet run and dotnet build?
A dotnet build only compiles the project and produces DLL files without executing. dotnet run compiles (if needed) and then automatically runs the program. Use dotnet run for convenient development debugging, and dotnet build for more controlled CI/CD builds.

📖 Summary

📝 Exercises

  1. Install the .NET 8 SDK on your computer and verify that dotnet --version outputs correctly. Record the version number
  2. Use dotnet new console -n Homework02 to create a project. Modify Program.cs to output your name and a greeting (e.g., "Hello, I'm Alex, starting to learn C#!"), then run it and take a screenshot
  3. Rewrite the top-level statements version from exercise 2 in the traditional Program.Main style, and confirm both produce the same output
  4. Intentionally introduce 3 compiler errors (missing semicolon, misspelling, omitted using), record the CS codes and error descriptions, and practice reading error messages
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏