01. .NET & First Program
C# is the language you write. .NET is the platform that builds and runs it: a runtime, a huge standard library, and the dotnet command-line tool.
From code to running program
The C# compiler does not produce machine code. It produces IL (Intermediate Language), packed into an assembly (.dll). When the program starts, the CLR (Common Language Runtime) compiles that IL into native code for your exact CPU. This step is called JIT (Just-In-Time) compilation.
Because every .NET language compiles to the same IL, the same runtime runs it on Windows, macOS, and Linux.
Your first program
A C# program is a list of statements, each ending with a semicolon. Console.WriteLine prints a line of text. The $ before a string lets you insert values with {braces}.
Console.WriteLine("Hello, World!");
string name = "Ada";
Console.WriteLine($"Welcome to C#, {name}.");Hello, World! Welcome to C#, Ada.
Run it from the project folder with dotnet run app/01-intro/Hello.cs. Change the text, run it again.
The long form
The file above uses top-level statements, a shortcut. Behind the scenes the compiler wraps your code in a class with a Main method, the entry point of every program. Older tutorials write it out in full:
namespace HelloWorld;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello from Main!");
}
}Hello from Main!
- A class groups data and behavior. You will build your own in lesson 05.
- A namespace groups related classes, like a folder.
Consolelives in theSystemnamespace. - An assembly (
.dllor.exe) is the compiled output of a project. An application is one or more assemblies.
Creating a real project
Single files are great for learning. Real apps are projects: a folder with a .csproj file that lists settings and packages.
dotnet new console -n MyApp
cd MyApp
dotnet runA Web API is just another .NET program. dotnet new webapi creates a project whose Program.cs also uses top-level statements:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/hello", () => "Hello, World!");
app.Run();Same language, same runtime, same dotnet run. It just listens for HTTP requests instead of exiting.