Glossary / Reference types
Reference types
A reference-type variable holds a reference to an object, rather than containing the object's fields directly. Classes, arrays, delegates, interfaces as variable types, and strings are reference types. Assignment copies the reference, so aliases can observe mutations to the same object; a reference can also be null unless constrained by nullable analysis and runtime checks.
Identity and assignment
var first = new List<int> { 1 };
var second = first;
second.Add(2);
// first also observes [1, 2]
The compile-time type controls which members are accessible and conversions, while the runtime type determines virtual dispatch and actual object layout. == behavior depends on the type's operator overload; ReferenceEquals tests object identity. Strings are reference types but immutable, and their equality operators compare text rather than reference identity.
Reference types are commonly allocated on the managed heap, but optimization and physical placement are implementation details; reason from identity and aliasing semantics. The garbage collector manages reachability, not deterministic resource disposal. Objects that own external resources should implement disposal patterns.
Engineering guidance
Make ownership and mutation explicit. Prefer immutable reference objects when sharing is useful without mutation risk. Avoid assuming an assignment clones an object; use deliberate shallow/deep copy APIs. Use nullable annotations and checks, while remembering runtime null can enter through reflection, interop, deserialization, or legacy code.
Interview questions
- What does assigning a class variable copy? The reference, not the object.
- Can two variables refer to one instance? Yes; mutations through either alias affect the same object.
- Does
==always compare identity? No; operators can be overloaded (strings compare values). - Does GC close files deterministically? No; use disposal for resources requiring timely release.
- What is runtime type used for? It supports virtual dispatch, type tests, and runtime object behavior.