Lesson 2 / 25
Projects, Program.cs and the dotnet CLI
Create, build and run a console project and read its project file.
A project is a .csproj plus source files
dotnet new console -n Hello creates a folder with Hello.csproj and Program.cs. The project file is short MSBuild XML: the SDK (Microsoft.NET.Sdk, or Microsoft.NET.Sdk.Web for web apps), the target framework (net10.0), and settings such as <Nullable>enable</Nullable> and <ImplicitUsings>enable</ImplicitUsings>. All .cs files in the folder are compiled automatically. Modern templates use top-level statements: Program.cs can contain statements directly, and the compiler generates the Main method for you; command-line arguments are available as args. Implicit usings add common namespaces such as System, System.IO, System.Linq and System.Collections.Generic. A solution (.sln or the newer .slnx) groups several projects, such as an app, a class library and a test project.
A first program
Top-level statements, string interpolation and reading input.
// Program.cs
Console.Write("Your name: ");
string? name = Console.ReadLine();
if (string.IsNullOrWhiteSpace(name))
{
name = "friend";
}
Console.WriteLine($"Hello, {name}! Today is {DateTime.Now:dddd}.");
Console.WriteLine($"You passed {args.Length} argument(s).");
// terminal:
// dotnet new console -n Hello && cd Hello
// dotnet run -- one twoThe csproj is the recipe card
The .csproj is the recipe card that says which kitchen (SDK), which cuisine (target framework) and which extra ingredients (packages). The .cs files are the dishes; dotnet build cooks them all.
Quick check: What do top-level statements in Program.cs do?
- Disable classes in the project
- Make the program run without the CLR
- Turn on nullable reference types
- Let you write statements directly; the compiler generates the Main method
Answer
Let you write statements directly; the compiler generates the Main method — The compiler wraps top-level statements in a generated entry point.