Skip to main content

Chapter 1: Fundamentals

This chapter introduces the basic development environment, the .NET execution model, and the C# type system. If you already know how to build and run .NET projects, you can skip to Section 1.4. We’ll then use a few simple examples to understand variable assignment, memory allocation, and object copying. These concepts form the foundation for immutable design, generics, and high-performance memory operations.

1.1 The design philosophy

C# is fundamentally an object-oriented language that emphasizes encapsulation, inheritance, and polymorphism. However, starting with C# 3.0, it began incorporating many of the best ideas from functional programming:

Functional feature C# implementation
Functions as values Delegates and lambda expressions
Declarative data processing LINQ query expressions
Immutability record, readonly struct, init accessors
Pattern matching switch expressions, the is operator

C# lets us combine object-oriented programming (OOP) and functional programming (FP) in the same program. We’ll cover the features in the table in later chapters.

Terminology

In programming languages, an expression is typically “a piece of code that can be evaluated and produces a value.” A statement, on the other hand, performs an action and usually does not directly produce a value.

Type safety: your first defense

C# is a strongly typed language with well-defined rules for operations and conversions between types. It also uses static typing: variable types are determined at compile time, so many type errors can be detected before the program runs. Chapter 2 introduces dynamic, which lets you defer certain type checks until runtime.

The following code shows how C# blocks an implicit conversion that could lose information:

// The compiler prevents this unsafe operation.
double pi = 3.14159;
int rounded = pi;  // ✘ Compile-time error: cannot implicitly convert

int rounded2 = (int)pi;  // ✔ Explicit cast; you're choosing to truncate

In this example, the compiler is not forbidding the conversion outright; it requires you to make the potential loss of information explicit. That design keeps risky operations from happening quietly in your code.

Using the type system effectively helps the compiler catch many errors early. Null safety, covered in Chapter 3, is another example.

1.2 Quick start

This section walks you through creating a minimal .NET project and observing how it compiles and runs. We’ll start with the command-line interface (CLI) so you can understand the .NET project structure and build pipeline.

Required tools

Before you begin, install the .NET 11 SDK (or later). You can choose your preferred development tool: Visual Studio 2026 Community (a full-featured IDE), Visual Studio Code (lightweight and cross-platform), or JetBrains Rider.

Your first .NET project

Open a terminal and run the following commands to create and run a console application:

dotnet new console --name HelloCSharp
cd HelloCSharp
dotnet run

The terminal will print:

Hello, World!

The project directory contains two essential files:

  • HelloCSharp.csproj: The project file defining target frameworks and dependencies.
  • Program.cs: The entry point, containing a single line of code by default:
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

Modern C# projects enable top-level statements by default. The compiler automatically synthesizes a Program class and Main method wrapper, eliminating the need for boilerplate code.

These three commands serve different purposes:

  1. dotnet new: Creates a project from a template. You only need it when creating a new project.
  2. dotnet build: Builds the project, compiling C# source code into an assembly containing Intermediate Language (IL).
  3. dotnet run: By default, builds the existing project and then runs it, so the commands above do not require a separate dotnet build.

What is IL (Intermediate Language)?

C# source code is usually not compiled directly into machine code for a specific CPU. Instead, it is first translated into IL (Intermediate Language). Because IL is independent of any particular CPU instruction set, the same compiled output can be executed by .NET runtimes across different platforms.

Under the standard JIT (Just-In-Time) execution model, the .NET Runtime compiles IL into platform-specific machine code dynamically as needed during program execution. Modern .NET also supports Native AOT, which compiles directly to native code ahead of time during publishing—another deployment model that doesn’t change our foundational understanding of JIT.

Running without a project: file-based apps

.NET 10 introduced file-based apps: a .cs file with top-level statements can run without a manually created project file. The following examples use .NET 11.

Save this as hello.cs:

#!/usr/bin/env dotnet
Console.WriteLine("Hello, C#!");
dotnet run --file hello.cs

The SDK still compiles the source. File-based apps remove manual project setup; top-level statements remove an explicit Main method. These are separate conveniences.

.NET 11 also supports #:include (available in .NET 10 SDK 10.0.300 and later). Create greeting.cs:

static class Greeting
{
    public static string Format(string name) => $"Hello, {name}!";
}

Then replace hello.cs with:

#!/usr/bin/env dotnet
#:include greeting.cs
Console.WriteLine(Greeting.Format("C#"));

The shebang supports direct execution on Unix-like systems; on Windows, use dotnet run --file hello.cs. Include paths are relative to the file containing the directive. Included files provide shared declarations rather than another set of top-level statements.

See the official documentation at the end of this section for other directives, such as #:package and #:property. These #: directives are processed by the SDK; they are not general C# syntax for arbitrary project source files.

File-based apps suit small tools and experiments. Projects remain useful for tests, resources, and team development; most examples in this book use projects.

Source code: DemoFileBased

See File-based apps and the .NET 11 SDK.

1.3 The .NET runtime architecture

The Hello World program in the previous section contains only one line of code, but it uses several parts of .NET. The base class library provides Console.WriteLine, while the runtime executes the program and manages memory. The following diagram and table show how these parts work together.

Layer Name Responsibilities
Top Application Layer Application frameworks (ASP.NET Core, MAUI, WPF, etc.)
Middle BCL (Base Class Library) Collections, I/O, string processing, networking, etc.
Bottom CLR (Common Language Runtime) JIT compilation, memory management, exception handling, etc.

Memory management is particularly important for the rest of this book. The garbage collector (GC) tracks the objects a program can still reach and reclaims memory occupied by unreachable objects. Reclaiming memory takes time. The more objects a program allocates in a short period, the more frequently the GC typically needs to run. This additional burden is called GC pressure.

Cross-platform support

Modern .NET supports Windows, macOS, Linux, and other platforms, including mobile devices and browsers. Many BCL APIs are cross-platform, so most console examples in this book are not tied to a particular operating system. Actual platform support depends on the frameworks, APIs, and dependencies the application uses.

Next, let’s look at how a program uses memory.

1.4 Stack and heap

Writing high-performance, bug-free code requires a solid understanding of memory allocation. The two foundational concepts here are the stack and the heap.

The stack and heap are both memory regions used while a program runs. Their most important difference is not simply which one is “faster,” but how memory is allocated and how its lifetime is managed.

Here is a simplified way to picture them:

  • Think of the stack as a stack of work trays used for method calls. Each method call adds a new stack frame to the top; when the method returns, that top frame is removed.
  • Think of the managed heap as an object store managed by the garbage collector (GC). An object does not disappear just because a particular method returns. It remains alive as long as the program can still reach it.

This analogy is about lifetime, not about the stack always being fast and the heap always being slow. Let’s now look at their characteristics separately.

The stack

The stack has several important characteristics:

  • A well-defined lifetime: A stack frame is created for a method call and released when that method returns.
  • Simple allocation: Creating or removing a stack frame generally requires only adjusting the stack’s current position, so the cost is low.
  • Limited space: Each thread has a limited amount of stack space. Excessive recursion or allocating too much stack space can cause a StackOverflowException.

Note

Although the stack is closely tied to method calls, not all local variables necessarily live on the stack. The compiler and JIT may place data in registers or use other storage arrangements because of closures or async state machines.

The heap

The managed heap has several important characteristics:

  • Lifetime determined by reachability: An object’s lifetime is not limited to a single method call. It remains alive as long as the program can still reach it, which supports data that must be shared across methods or retained for longer periods.
  • Usually more available space: Compared with the limited stack assigned to each thread, the managed heap can generally accommodate larger objects and data structures whose capacity grows dynamically.
  • GC management: Objects on the heap normally carry extra information such as object headers, and the GC must later track, scan, and reclaim them. Modern .NET heavily optimizes ordinary small-object allocation, but frequent or large allocations still add management cost and create GC pressure.

For these reasons, it is misleading to reduce the distinction to “the stack is fast and the heap is slow.” Nor can you determine where data must live simply from how large it is or how long it survives. As the next section shows, type semantics and physical memory placement are related concepts, but they are not the same thing.

1.5 Value types and reference types

In C#, assigning one variable to another sometimes gives you an independent copy of the data, but sometimes both variables refer to the same object. The difference depends on the type.

The most important distinction between value types and reference types is whether a variable holds the value itself or a reference to an object. First understand what assignment copies, then consider where the data actually lives in memory. These questions are related, but they are not the same.

Value types

Value types include:

  • All numeric types (int, double, byte, decimal, …)
  • bool, char
  • enum
  • struct (including DateTime and Guid)

Behavioral characteristics:

  • They contain the data directly.
  • Assigning one to another variable copies the entire value (copy by value).

Think of it like photocopying a physical document. If you hand a copy to a coworker (assignment), and they write on their copy (mutating their variable), your original document remains unaltered.

The following example demonstrates this value-type behavior: assignment copies the value itself.

int a = 10;
int b = a;  // Copies 10 into b
b = 99;     // Changing b does not affect a
Console.WriteLine(a); // Prints 10

Line 3 changes b, but a remains unchanged because each variable holds its own integer value. If a value type is a struct with reference fields, assignment also copies those references, not the objects they refer to. Section 1.7 explains this in more detail.

Source code: DemoValueTypes

Reference types

Reference types include:

  • class (for example, string and object)
  • Arrays (for example, int[])
  • interface
  • delegate (delegates and lambdas are covered in Chapter 8, and events in Chapter 9)
  • record or record class (record struct is a value type; see Chapter 4)

Note

string is also a reference type, but a string object’s contents cannot be changed (a property called immutability). Even if two variables refer to the same string, neither can modify its contents and affect the other.

Behavioral characteristics:

  • They store a reference (a memory address) that points to an object on the heap.
  • Assigning one to another variable copies only the reference, resulting in both variables pointing to the same object.

It’s like sharing a link to a cloud document. You send your coworker the link (assignment). Both of you hold a copy of the link (the reference), and both copies point to the exact same online document (the object). If your coworker edits the document through their link, you’ll instantly see those changes.

With reference types, assignment behaves differently. In the following example, user2 receives a reference to the same object:

var user1 = new User { Name = "Alice" };
// Copies the reference; user1 and user2 point to the same object
var user2 = user1;
user2.Name = "Bob";  // Changing the shared object through user2 is visible through user1
Console.WriteLine(user1.Name); // Prints Bob

Therefore, when you modify Name through user2, user1 sees the modified state of that same object.

Source code: DemoReferenceTypes

Array layout: value vs reference elements

An array itself is a reference type, but its elements can be either value types or reference types. The distinction is whether the array stores values themselves or references to objects in contiguous memory. This also affects data-access efficiency and GC pressure.

Arrays of value-type elements

Consider this example:

long[] numbers = new long[3]; // Each long is 8 bytes
numbers[0] = 12345;
numbers[1] = 54321;
numbers[2] = 99999;

In the usual allocation model, the runtime obtains one contiguous block of memory for the array, and the three long values are stored directly within it. An array object like this is normally allocated on the managed heap. Concretely:

  • Array header: Includes metadata such as the array length.
  • Contents: Stores the raw values (like 12345) packed tightly.
  • Result: Conceptually, there is a single array object; the data is dense and usually has good memory locality.

Arrays of reference-type elements

Next, consider an array whose element type is StringBuilder:

StringBuilder[] builders = new StringBuilder[3];
builders[0] = new StringBuilder("builder1");
builders[1] = new StringBuilder("builder2");
builders[2] = new StringBuilder("builder3");

In this scenario, the array stores references, not the actual string data:

  • Array header: Includes metadata such as length.
  • Contents: Stores references (addresses) to StringBuilder objects.
  • Actual objects: Usually allocated separately; they are not guaranteed to be contiguous with the array elements.
  • Result: There are normally multiple allocations—the array itself and each StringBuilder object—and data locality may be poorer.

This leads to two important effects:

  1. Locality: value-type arrays store elements contiguously, so CPU cache hit rates tend to be higher.
  2. GC pressure: Creating a separate object for every element, as in the example above, increases allocation and GC work. However, an array of reference-type elements can also store references to existing objects; it does not have to create a new object for each element.

Key takeaways for this section:

  • Whether you’re using a value type or a reference type, data still has to live somewhere in memory.
  • Call-related data and many locals are often represented in a stack frame or in registers, but that is ultimately a runtime/JIT implementation detail.
  • The key property of a value type is that it stores its data directly; that data may appear in a local, inside a heap object, or inside an array element.
  • A reference-type variable stores a reference; the object it points to is typically allocated on the heap.

Note

Chapter 13 introduces a special value type, Span<T>. The span itself has strict lifetime restrictions, but it can access memory in different locations. This is another example of why type and memory placement are not the same thing.

Food for thought: common type gotchas

After reading the examples above, consider what happens if you assign an int[] variable to another variable and then modify an array element. What will the original variable see? Predict the result, then run the array example in DemoReferenceTypes to check it. If the result differs from your prediction, explain what was copied and how the array type relates to its element type.

1.6 Boxing and unboxing

Boxing and unboxing are mechanisms that allow value types to be treated as objects, but they come with additional performance costs.

Boxing

Simply put, boxing wraps a value of a value type in an object. For example, assigning an int value to an object variable causes boxing.

Imagine picking an apple (a value type). Normally, you use it directly as a raw value. But if you now want to treat it as a general-purpose object stored in a warehouse (the heap), you must place it inside a physical box (boxing) and slap a tracking label on it. Obtaining the box and packing the item adds overhead.

What happens during boxing? For an int, the CLR creates an object, copies the original integer value into it, and returns a reference to that object. This normally requires a heap allocation.

First, here is a minimal boxing example:

int i = 123;
object o = i; // Boxing: wraps the int in a heap-allocated object

Here, o refers to the boxed object containing 123. Changing i afterward does not change the integer stored in that object.

Note

Even if the original integer is already stored on the heap (for example, as an array element), boxing copies its value into a separate object. Besides converting to object, converting a value to an interface type it implements can also cause boxing. The JIT compiler in modern .NET can sometimes eliminate the allocation without changing program behavior.

Unboxing

Unboxing is the reverse process: converting an object back into a value type.

Unboxing checks that the object contains a value of the requested type, then extracts the value and copies it to the destination.

When unboxing, you must explicitly specify the value type you want to retrieve:

int j = (int)o; // Unboxing

If o does not actually contain an int, this line throws an exception at runtime.

Why it matters

Boxing typically has two main costs:

  1. CPU work: Copying data and allocating memory.
  2. GC pressure: Boxing creates extra heap objects, giving the garbage collector more work.

Hidden boxing traps often occur when using older, non-generic collections (like ArrayList) or certain string formatting methods. Because ArrayList stores every element as object, adding a value type automatically triggers boxing. Here’s a common example:

int x = 10;
// Trap: string.Format takes object parameters
string s = string.Format("Score: {0}", x); // x gets boxed!

// Modern approach: string interpolation (often optimized by the compiler)
string s2 = $"Score: {x}";

Source code: DemoBoxingUnboxing

Whether string interpolation causes boxing depends heavily on your compiler version and the specific code. In modern C# and .NET, interpolating value types (like int) is highly optimized and typically avoids falling back to the boxing string.Format(object, ...) path, though you may still incur string allocations.

If you have heavy string formatting on a performance-critical hot path, more reliable optimization approaches include:

  • Avoid APIs that primarily take object parameters (for example, some params object[] overloads).
  • If formatting itself becomes a performance bottleneck, consider APIs that write directly to a buffer to reduce temporary string allocations. Chapter 13 introduces the fundamentals of these memory operations.
  • Prefer generic collections, such as List<int> instead of ArrayList.
  • String interpolation is introduced in Chapter 2 (Section 2.7).
  • Generics are covered in Chapter 7.

1.7 Copying objects and arrays

As we’ve seen, assigning a reference-type variable does not create a new object. When copying objects or arrays, we also need to consider whether the copy shares internal data with the original. This is the main distinction between a shallow copy and a deep copy. C# and .NET do not provide a universal deep-copy mechanism for arbitrary objects.

Shallow vs deep copy for objects

A shallow copy copies only the top-level object itself. If that object contains reference-type fields, those fields will still point to the exact same inner objects:

class Team
{
    public string Name { get; set; } = string.Empty;
    public List<string> Members { get; set; } = new();

    // Uses object.MemberwiseClone() to copy instance fields
    // (shallow copy)
    public Team ShallowCopy() => (Team)MemberwiseClone();
}

var team1 = new Team
{
    Name = "Dev",
    Members = new List<string> { "Alice", "Bob" }
};

var team2 = team1.ShallowCopy(); // Shallow copy
team2.Name = "QA";               // Changes only team2's Name reference
// But Members still points to the same List!
team2.Members.Add("Charlie");

Console.WriteLine(team1.Members.Count); // Prints 3 (affected!)

This demonstrates a classic shallow-copy bug: the internal List is not duplicated; only the reference to it is. As a result, adding an element to team2.Members inadvertently mutates team1.Members.

Source code: DemoShallowCopy

Early .NET provided the ICloneable interface, but its Clone() method returns object (lacking strong typing) and carries ambiguous semantics—one cannot tell from the interface whether it performs a shallow or deep copy. In practice, avoid relying on it as a public contract; use explicitly named methods (like ShallowCopy) or strongly typed copy constructors instead.

Note

Another common modern approach is using record types with the with expression (Chapter 4). Remember that with performs a shallow copy by default; if members contain mutable nested reference types, internal objects are still shared across copies.

If you need to provide a deep copy, you must explicitly decide which members require new instances. The following example demonstrates how to implement a deep copy with a copy constructor:

class Team
{
    public string Name { get; set; } = string.Empty;
    public List<string> Members { get; set; } = new();

    public Team() { }

    public Team(Team original)
    {
        // string is immutable, so copying its reference
        // does not introduce shared mutable state.
        Name = original.Name;

        // Create a new List to prevent sharing the Members
        // collection with the original object.
        Members = new List<string>(original.Members);
    }
}

var team1 = new Team
{
    Name = "Dev",
    Members = new List<string> { "Alice", "Bob" }
};

// Create an object copy using the copy constructor
var team2 = new Team(team1);
team2.Members.Add("Charlie");
Console.WriteLine(team1.Members.Count); // Prints 2 (team1 is unaffected)

The key line is:

Members = new List<string>(original.Members);

Because the elements are immutable string instances, copying their references is sufficient.

Source code: DemoDeepCopy

In this example:

  • The Name property reuses the original string reference without issue. Because string is immutable, calling Replace or ToUpper does not change the original string’s contents. The returned string is not necessarily a new object. Conversely, Members is a List<string> (a mutable collection), which must be newly instantiated to avoid shared state.
  • Copy constructors are particularly well-suited when you need fine-grained control over copy logic. They provide strong typing and represent the standard approach for custom cloning in .NET.

Note

For an in-depth discussion of immutability, see Chapter 4: Immutable Design.

Summary of common object copying approaches and their trade-offs:

  • Copy constructor: Strongly typed with explicit logic, offering fine-grained control over shallow and deep copy boundaries; requires maintaining boilerplate when types have many members.
  • record with with: Clean and concise, ideal for non-destructive mutation of immutable data, but performs a shallow copy by nature (Chapter 4).
  • JSON serialization / deserialization: System.Text.Json can duplicate entire object graphs automatically, serving as a convenient fallback; however, it depends on public serialization contracts, type support, and circular-reference configurations, carrying extra performance overhead. It is not an unconditional universal deep copy.
  • ICloneable.Clone(): Weakly typed with ambiguous semantics; avoid in modern code.

Shallow vs deep copy for arrays

Array copying follows the same principle as object copying: Array.Clone() performs a shallow copy.

If the array element type itself does not contain mutable reference state, such as int or string, a shallow copy is often enough. The following example copies an int[]:

int[] original = { 1, 2, 3 };
int[] copy = (int[])original.Clone();
copy[0] = 999;
Console.WriteLine(original[0]); // Prints 1 (unaffected)

Be careful, though: this works because int is just the value itself. If the array element type is a struct that contains reference-type fields, Array.Clone() still performs only a shallow copy of those inner references, so it does not automatically give you full isolation.

If the array elements are reference types, be careful:

var original = new StringBuilder[]
{
    new StringBuilder("A"),
    new StringBuilder("B")
};
var copy = (StringBuilder[])original.Clone();
copy[0].Append("!"); // Mutating copy also mutates original!
Console.WriteLine(original[0]); // Prints "A!" (affected!)

The output is A!. Although Array.Clone() creates a new array object, the elements inside still point to the same StringBuilder objects as original, so mutating copy[0] also affects original[0].

To make the mutable objects in the two arrays independent as well, create a new object for each StringBuilder in this example:

var original = new StringBuilder[]
{
    new StringBuilder("A"),
    new StringBuilder("B")
};

var deepCopy = new StringBuilder[original.Length];
for (int i = 0; i < original.Length; i++)
{
    deepCopy[i] = new StringBuilder(original[i].ToString());
}
deepCopy[0].Append("!");
Console.WriteLine(original[0]); // Prints "A" (unaffected)

This time the output is A. Both approaches create a new array. The difference is that the shallow copy still shares the original StringBuilder objects, while the deep copy also creates copies of those objects. Changing the contents of deepCopy[0] therefore does not affect original[0].

Source code: DemoDeepCopyArray

Summary

  • File-based apps run a .cs file without a manually created project; #:include can share declarations across files.
  • C# design philosophy: An OOP + FP hybrid with strong type safety that lets the compiler help prevent potential bugs.
  • Execution model: A typical .NET build first compiles C# source code into IL. In the usual JIT execution model, the CLR compiles that IL into machine code at runtime and handles runtime services such as garbage collection.
  • Stack vs heap: A stack frame’s lifetime is tied to a method call, while the managed heap uses reachability and the GC to manage object lifetimes. The distinction should not be reduced to “stack fast, heap slow.”
  • Value types vs reference types: Value types contain data directly, while reference types store references to objects; you can think of a reference as a memory address that points to an object.
  • Array memory characteristics: Arrays of value types store values contiguously; arrays of reference types store references contiguously. Creating a separate object for each element may increase allocations and GC pressure.
  • Boxing/unboxing: Boxing wraps a value in an object; unboxing extracts the value from the boxed object. Both can introduce extra cost.
  • Object copying: MemberwiseClone(), Array.Clone(), and default with copying do not recursively copy nested objects. To isolate mutable state, design the copy explicitly. Serialization is also an option for data that meets the serialization contract.

Glossary

Term Description
BCL Base Class Library; collections, I/O, networking, and other fundamental APIs
Boxing Wrapping a value of a value type in an object, for example converting int to object
CLI (command line interface) A text-based interface for interacting with the computer
CLR Executes .NET code and manages memory; in the JIT execution model, it also compiles IL into machine code
GC (garbage collector) Automatically manages and reclaims heap memory
Heap Memory region where objects live; managed by the GC
IL (intermediate language) Platform-independent compiled output for .NET languages
Immutable Cannot be changed after creation (for example, string)
JIT (Just-In-Time compilation) Compiles IL to machine code at runtime
Reference type Stores a reference/address to an object (for example, class, string)
Stack Memory region whose call frames are created and released along with method calls
Top-level statements Write statements without explicitly defining a Program class
Unboxing Extracting a value of a value type from a boxed object
Value type Stores data directly (for example, int, struct)