liveBook · Manning

Reference type

As explained in .NET in Action, Second Edition

A reference type is a .NET type whose values identify objects or locations containing the type's data.

A reference type stores a reference to its data rather than containing the data directly. Classes and strings are reference types; structs and integers are value types. The distinction affects copying, method parameters, and nullability. section 2.4 section 5.2.2

Reference types matter in several practical situations:

  • References resemble pointers conceptually, but C# manages them differently and automatically boxes value types when an object is required. section 2.4
  • Reference types can be null. Nullable reference type annotations such as string? explicitly allow null and help the compiler identify unsafe usage. section 5.2.2
  • A nonnullable property can be initialized with a default value or required through a constructor, preventing objects from being created without essential data. section 5.2.2

Requiring a nonnull reference

A Book class can require its Title reference through a constructor: public Book(string title) { Title = title; }. Creating new Book(null) then produces a compiler warning because Title is nonnullable, while new Book("Blah") satisfies the declared contract. section 5.2.2

Listing 5.7 Book constructor
public class Book
{
  public int Id { get; set; }          #1
  public string Title { get; set; }    #2
  
  public Book(string title)            #3
  {
    Title = title;                     #4
  }
}

Inspect the Book constructor and its Title property to see how a reference-type invariant is enforced during object creation. section 5.2.2

How .NET in Action, Second Edition covers it

How deep it goes
Defines storage differences and applies nullable annotations and constructors, but defers detailed reference mechanics to a later section.
Examples
Demonstrates strings, integers passed to object parameters, and a Book whose Title is initialized or required by constructor.
What it assumes
Teaches the reference-versus-value distinction while assuming familiarity with basic C# classes, properties, and object creation.
What you can do after
Apply reference-type annotations and constructors to prevent unintended null values in C# object models.
How it connects
Connects reference types with value types, classes, strings, boxing, nullable reference types, constructors, and compiler warnings.

Also explained in

Compare how 2 books explain reference type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.