The Analogy: The Sheet Music and the Stage Crew
C# is the sheet music: precise notation describing exactly what should happen. .NET is the venue — the stage, the instruments, the lighting rig and the crew who clear up afterwards. You write the score; the crew handles memory, threads, file handles and the thousand details that would otherwise be yours.
That division is what "managed" means, and it is the single biggest difference from C. In C you asked malloc for memory and freed it yourself, and forgetting was a leak. In C# a garbage collector reclaims what nothing references any more. You give up precise control over when that happens, and in exchange an entire category of bug — dangling pointers, double frees, use-after-free — simply cannot occur in ordinary code.
C# is not a Windows-only language and has not been for years. The same source builds and runs on Linux, macOS and Windows, and it powers web APIs (ASP.NET Core), desktop apps, cloud services, and the majority of Unity games.
Syntax or Core Structure
using System;
class Program
{
static void Main(string[] args)
{
string name = "Ada";
int commits = 3;
double coverage = 0.87;
Console.WriteLine("Hello, C#!");
Console.WriteLine($"{name} pushed {commits} commits");
Console.WriteLine($"coverage: {coverage:F2}");
Console.WriteLine($"args received: {args.Length}");
}
}
Output:
Hello, C#!
Ada pushed 3 commits
coverage: 0.87
args received: 0
Main is the entry point: the runtime looks for it by that exact name, with a capital M. args holds whatever followed the program name on the command line, so it is empty when you just dotnet run.
The $ before a string turns it into an interpolated string: anything inside { } is evaluated and formatted in place. {coverage:F2} means "fixed-point, two decimals". This replaces the string concatenation you would write in C or older Java, and it is the idiomatic choice in modern C#.
The same program, modern style
// Program.cs — top-level statements, C# 9 and later
string name = "Ada";
Console.WriteLine($"Hello, {name}!");
No class, no Main, no using System;. The compiler generates the class and entry point for you, and the project template supplies the common using directives implicitly. Both forms compile to the same thing; new templates produce this one, while the explicit form is what you will see in older code and in every file that holds more than the entry point.
Getting a project running
dotnet new console -o Receipts
cd Receipts
dotnet run
| Command | What it does |
|---|---|
dotnet new console -o Name | creates a project folder with Program.cs and a .csproj |
dotnet run | builds if needed, then runs |
dotnet build | compiles to a .dll under bin/ without running |
dotnet test | discovers and runs unit tests |
dotnet publish -c Release | produces a deployable build |
The .csproj file is where the target framework, language version and package references live. It is XML, it is short, and it is worth reading once early rather than treating as magic.
Technical Depth: What Happens Between Source and CPU
C# is compiled twice. The first pass, done by dotnet build, turns your source into IL (Intermediate Language) and packs it into an assembly — a .dll file that also carries metadata describing every type inside it. IL is not machine code; it targets an abstract stack machine and knows nothing about x64 or ARM.
The second pass happens at run time. The CLR (Common Language Runtime) loads the assembly and its JIT compiler translates each method into native code the first time that method is called. So the first call to a method is slower than the thousandth, and the JIT can optimise for the exact CPU it finds itself on — something an ahead-of-time compiler cannot do.
| Stage | Producer | Output | When |
|---|---|---|---|
| Compile | Roslyn (dotnet build) | IL in a .dll | build time |
| Load | CLR assembly loader | types in memory | process start |
| JIT | CLR | native machine code | first call per method |
| Collect | GC | reclaimed memory | when a generation fills |
Types, and the one distinction that matters most
Every C# type is either a value type or a reference type.
int a = 5;
int b = a; // b is a separate copy
b = 9; // a is still 5
int[] xs = { 1, 2, 3 };
int[] ys = xs; // ys refers to the SAME array
ys[0] = 99; // xs[0] is now 99 too
int, double, bool, char, decimal and every struct are value types: assignment copies the contents. string, arrays, and every class are reference types: assignment copies the reference, and both names then see the same object. Almost every surprising bug in a first month of C# traces back to this line.
string is a reference type that behaves like a value type, because strings are immutable. s.ToUpper() does not change s; it returns a new string.
var is not dynamic typing
var count = 42; // compiler infers int
var names = new List<string>();
count = "hello"; // COMPILE ERROR - count is int, permanently
var asks the compiler to write the type for you from the right-hand side. The variable is just as strongly typed as if you had spelled it out, and the error above is caught at build time. (dynamic genuinely defers type checking to run time; it exists, it is rare, and it is not var.)
Nullable reference types
New projects enable this by default in the .csproj:
<Nullable>enable</Nullable>
Under it, string name promises never to be null and string? name admits it might be. The compiler then warns when you dereference something that could be null, or assign null to something that claims it cannot be. It is a warning system rather than a runtime guarantee, and it turns a large class of NullReferenceException into build-time feedback. Module 8 covers it properly.
Where C# sits
| C# | Java | Python | C++ | |
|---|---|---|---|---|
| Memory | GC | GC | GC | manual / RAII |
| Typing | static, inferred | static | dynamic | static |
| Compiles to | IL, then JIT | bytecode, then JIT | bytecode, interpreted | native |
| Value types | user-definable struct | primitives only | none | yes |
Properties, async, LINQ | built in | partly / library | partly | no |
Real World Example: A Receipt Printer
A first program worth keeping: read a small table of line items, compute each value and the total, and print it aligned. This is the shape of every reporting task you will ever write.
using System;
record Line(string Name, int Qty, decimal Price);
class Program
{
static void Main()
{
var lines = new[]
{
new Line("bolt", 250, 0.35m),
new Line("nut", 480, 0.20m),
new Line("washer", 120, 0.10m),
new Line("bracket", 30, 4.75m),
};
decimal total = 0m;
Console.WriteLine($"{"item",-10}{"qty",5}{"price",9}{"value",10}");
foreach (var line in lines)
{
decimal value = line.Qty * line.Price;
total += value;
Console.WriteLine($"{line.Name,-10}{line.Qty,5}{line.Price,9:F2}{value,10:F2}");
}
Console.WriteLine(new string('-', 34));
Console.WriteLine($"{"total",-10}{"",5}{"",9}{total,10:F2}");
}
}
Output:
item qty price value
bolt 250 0.35 87.50
nut 480 0.20 96.00
washer 120 0.10 12.00
bracket 30 4.75 142.50
----------------------------------
total 338.00
Four details in that program are worth naming.
0.35m is a decimal, not a double. The m suffix matters. double stores base-2 fractions, so 0.1 + 0.2 is not exactly 0.3 and a long column of money slowly drifts. decimal stores base-10 digits and is what you use for currency, always.
{value,10:F2} is width then format. The number after the comma is a field width — positive pads on the left, negative pads on the right — and the part after the colon is the format string. That single feature replaces printf's %-10s and %9.2f.
record Line(...) declares an immutable data holder in one line. The compiler writes the constructor, the read-only properties, value equality and a readable ToString for you. Module 8 covers records; here it just saves twelve lines of boilerplate.
var lines = new[] { ... } infers both types. The array becomes Line[] because every element is a Line, and var picks that up.
The reason the total row lines up is that the widths sum to a constant: 10 + 5 + 9 + 10 = 34 characters, which is exactly the length of the separator produced by new string('-', 34).
Common Mistakes
- Writing
maininstead ofMain. C# is case-sensitive and the runtime looks for the capitalised name. A lowercasemaincompiles as an ordinary method and the build fails with "does not contain a static 'Main' method suitable for an entry point". The same habit producesconsole.writeline, which does not resolve at all. - Using
doublefor money.double total = 0.1 + 0.2;is0.30000000000000004, and after a few hundred rows a report is visibly wrong. Usedecimalwith themsuffix on literals. - Expecting the file name to match the class name. That is a Java rule, not a C# one.
Program.csmay containclass Invoice, and one file may hold several types. Matching them is a convention worth following, not a requirement. - Mixing top-level statements with an explicit
Main. A project may have one entry point. IfProgram.csstarts with bare statements, adding aclass Programwithstatic void Mainelsewhere gives "cannot have both", and the fix is to pick one style. - Running
dotnet runfrom the wrong directory. The command looks for a project in the current folder, so running it from the solution root with several projects underneath fails with "MSB1011: more than one project".cdinto the project folder, or pass--project. - Assuming assignment copies an object.
var b = a;on aListor an array gives two names for one object, and mutating through either is visible through both. Only value types copy. - Confusing .NET Framework with .NET. The old Windows-only .NET Framework stops at 4.8 and is closed to new features. Modern, cross-platform .NET numbers from 5 upward. Tutorials written for the former often will not build on the latter, and vice versa.
- Treating a compiler warning as noise. Nullable warnings in particular are the compiler telling you a
NullReferenceExceptionis reachable. Left unread they accumulate until nobody reads any of them.
Best Practices
- Start every project with
dotnet new consoleor a real template rather than a bare.csfile — you get the.csproj, the implicit usings and nullable checking already switched on. - Follow the standard casing:
PascalCasefor types, methods and properties,camelCasefor locals and parameters,_camelCasefor private fields. Every C# codebase you meet will use it. - Prefer string interpolation to concatenation.
$"{name} has {count} items"reads better than the+chain and formats numbers without a separate call. - Use
varwhen the right-hand side already names the type (var list = new List<int>();) and an explicit type when it does not (int total = Compute();). Readability is the only rule here. - Use
decimalfor money,doublefor measurements and physics,intfor counts. Picking the type once at the top saves rounding arguments later. - Keep
Mainshort. Parse arguments, call one method, return an exit code; put the real work in named methods that can be tested. - Turn on
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>early in a new project, while there are no warnings to fix. - Let the garbage collector do its job. Calling
GC.Collect()by hand almost always makes throughput worse; the exception isIDisposable, whereusingreleases file handles and sockets deterministically.
Practice Exercises
- Create a console project with
dotnet new console -o Greeter, then make it print your name, the current year as a hard-coded number, and the result of7 * 6— each on its own line, using a single interpolated string per line. - Declare an
int, copy it to a second variable, change the copy, and print both. Do the same with a two-element array. Print all four values and explain in a comment which pair changed together and why. - Extend the receipt printer with a fifth line item of your choosing, then add a row showing the average value per item formatted to two decimals. Keep the columns aligned by reusing the same width specifiers.
- Write the receipt totals twice, once accumulating into a
decimaland once into adouble, using prices of0.1,0.2and0.3with quantity 1. Print both totals with:F17and describe the difference you see.