skip to content

Struct and Class Semantics

Value types copy on assignment and reference types share one object, which explains boxing, struct pitfalls and equality surprises. Interviewers start C# here.

on this pageshow

explore

questions

28

In C#, what happens when an int is assigned to an object variable, and what does casting it back to int do?

level: juniorimportance: must knowfreq 80%

answer

  1. a heap object for a value
  2. what the variable actually holds
  3. the cast checks the type
  4. two boxes, two identities

basics

~20 s

Assigning an int to object boxes it: the runtime allocates a heap object and copies the value in. Casting back unboxes it: the runtime checks the box holds an int and copies the value out. Later changes to the local never reach the box.

solid answer

~40 s

Boxing is the implicit conversion from a value type to `object` (or to an interface the type implements). The runtime allocates a new object on the managed heap, copies the `int` into it and hands back a reference. The box is a snapshot: assigning a new value to the original local afterwards does not change it. Unboxing is the explicit cast `(int)o`; the runtime first checks that `o` really holds a boxed `int` (throwing `InvalidCastException` if it holds another type, `NullReferenceException` if `o` is null) and then copies the value out. Every boxing conversion creates a separate object, so two boxed 7s compare `false` with `==` on `object`, which compares references, and `true` with `Equals`, which compares the values.

code

csharp · 13 lines
csharp
int count = 42;
object boxed = count;      // boxing: a new heap object holding a copy of 42
count = 100;               // changes the local variable only

Console.WriteLine($"count = {count}, boxed = {boxed}");   // count = 100, boxed = 42

int back = (int)boxed;     // unboxing: check the box holds an int, then copy it out
Console.WriteLine(back);                                   // 42

object first = 7;
object second = 7;                                         // a second, separate box
Console.WriteLine(first == second);                        // False: == on object compares references
Console.WriteLine(first.Equals(second));                   // True: Int32.Equals compares the values

go deeper

for a junior

Recall the two steps: boxing allocates a heap object holding a copy, and unboxing checks the type and copies the value back out. Show that changing the original afterwards leaves the box untouched.

for a middle

Explain why == on two object variables compares references while Equals compares the boxed values, and name the places the compiler inserts a box for you: object parameters, object fields and interface variables.

for a senior

Connect boxing to allocation pressure: each box is a short-lived heap object, so boxing in a per-request or per-frame loop turns into garbage collections. Name the generic, typed alternative for each case.

for a principal

Treat an object-typed API for numbers as a cost every caller pays in allocations, and weigh one simple object signature against generic or strongly typed overloads that keep values unboxed.

## Value types, reference types and `object` C# has two families of types. A **value type** (`int`, `double`, `bool`, `DateTime`, any `struct` or `enum`) holds its data directly: a local of type `int` *is* the four bytes of the number. A **reference type** (`string`, `object`, any `class`, any interface) is a reference to an object that lives on the **managed heap**. Yet every type, `int` included, derives from `System.Object`, so a C# program can treat any value as an `object`. **Boxing** is the mechanism that makes that possible for value types. ## What boxing does `object boxed = count;` compiles without a cast because boxing is an **implicit** conversion. At run time it performs these steps: 1. Allocate a new object on the managed heap, large enough for an object header, a pointer to the type's method table and the value itself (24 bytes for an `int` on a 64-bit .NET 10 process). 2. Copy the current value of `count` into that object. 3. Return a reference to the new object, which is what `boxed` now holds. The same happens when a value type is converted to an **interface** it implements, for example `IComparable<int> c = count;`, because an interface type is a reference type too. ## What unboxing does Getting the value back needs an **explicit** cast, `(int)boxed`. Unboxing runs two steps: 1. **Check** that the reference points at a boxed value of exactly the target type. A box of another type throws `InvalidCastException`; a null reference throws `NullReferenceException`. 2. **Copy** the value out of the box into the target variable. Unboxing does not allocate. Its cost is the type check and the copy, which Microsoft's documentation describes as expensive to a lesser degree than boxing. ## The box is a copy Because step 2 of boxing copies the value, the box and the original variable are independent from that moment on: ```csharp int count = 42; object boxed = count; // box holds 42 count = 100; // only the local changes Console.WriteLine(boxed); // 42 ``` Nothing links `boxed` back to `count`. The same is true in the other direction: the value you unbox is a fresh copy, and changing it does not touch the box. ## Every box is a new object Each boxing conversion allocates its own object, even for equal values. That matters as soon as code compares two `object` variables: | Expression | Result | Why | |---|---|---| | `first == second` (both `object`, both boxed 7) | `false` | `==` on `object` compares references, and these are two boxes | | `first.Equals(second)` | `true` | the virtual call reaches `Int32.Equals`, which compares the values | | `(int)first == (int)second` | `true` | both sides are unboxed to `int` first | .NET keeps no cache of boxed integers, so there is no range of small numbers for which two boxes happen to be the same object. Equality rules in general are covered with equality and hashing; the point here is only that a box has an identity of its own. ## Why it matters - **Allocation.** Every box is a heap object the garbage collector must later reclaim. One box is cheap; a box per item per request or per frame is steady garbage. - **Hidden conversions.** No syntax marks a boxing conversion. Passing an `int` to a parameter of type `object`, storing it in an `object` field, adding it to a non-generic collection or assigning it to an interface variable all box silently. - **Copies diverge.** Code that boxes a value and keeps using both the box and the original is working with two copies. - **Generics avoid it.** `List<int>` stores `int` values directly in an `int[]`, while the older `ArrayList` stores `object` references and so boxes every element it is given. ## Spotting a box in everyday code Boxes a beginner writes without noticing: - `Console.WriteLine("{0} items", count)`: the composite-format overloads take `object?` arguments. - `var bag = new ArrayList { count };`: every element of `ArrayList` is an `object`. - `object setting = 30;` in a settings class with `object`-typed properties. - `IComparable<int> c = count;`: an interface variable holding a value type. A good habit is to ask, whenever a value type meets a parameter, field or collection typed `object` or an interface: is a box being made here, and does the code need it?

  • If int derives from object, why does calling ToString() on a plain int local not box it?
    `int` is an alias for the struct `System.Int32`, which overrides `ToString`. When a struct overrides the method, the call runs the struct's own implementation directly on the variable, so no box is needed. Boxing happens when the value has to become an `object` or interface reference: an `object` parameter or field, an interface variable, or a call to a method the struct only inherits from `ValueType`.
  • Does unboxing allocate memory the way boxing does?
    No. Unboxing checks the box's type and copies the value out into the target variable; nothing new is created on the heap. In a box-and-unbox round trip the only allocation is the box itself. Unboxing still costs the type check and the copy, so it is cheaper than boxing but not free.

Boxing is like photocopying a form and sealing the copy in a labelled envelope: anyone who accepts any envelope can carry it, but editing your original form later changes nothing inside, and the envelope opens only for someone asking for exactly that form.

  • The object variable points at the original int local, so later changes show up in both.
  • Boxing is free because an int already is an object.
  • Two boxed 7s are equal with == on object because the values match.
  • Unboxing allocates a new int on the heap.
  • Boxing only happens when you write an explicit (object) cast.
open as a page

In C#, what do ==, Equals and object.ReferenceEquals each compare for two strings, and why does that change when they are typed as object?

level: juniorimportance: must knowfreq 80%

basics

~20 s

In C#, == is picked at compile time from the operands' static types: string's overload compares characters, but on two object-typed variables it tests references. Equals is virtual and still compares content; ReferenceEquals always tests identity.

open as a page

In C#, `string` is a reference type, so why does a method that appends to its `string` parameter leave the caller's string unchanged?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Strings are immutable: s += x builds a new string and stores it in the method's own parameter, which is a copy of the caller's reference. The caller's variable still refers to the original string, which nothing can change.

open as a page

In C#, what happens when you assign a struct variable to another variable and change the copy, versus doing that with a class instance?

level: juniorimportance: must knowfreq 85%

basics

~20 s

Assigning a struct copies the whole value, so changing the new variable leaves the original untouched. Assigning a class instance copies only the reference, so both variables reach one object and an edit through either shows through both.

open as a page

In C#, when should you declare a type as a struct rather than a class, and when is a class the better choice?

level: juniorimportance: must knowfreq 78%

basics

~20 s

Choose a struct for a small, immutable type that represents one logical value, stays valid when all-zero and is rarely boxed, such as a coordinate or a timestamp. Choose a class for identity, inheritance, or large or changing state.

open as a page

In C#, how does a tuple written as (int Id, string Name) differ from System.Tuple<int, string>?

level: juniorimportance: must knowfreq 60%

basics

~10 s

C# tuple syntax builds System.ValueTuple, a struct with public mutable fields and optional element names. System.Tuple is an older immutable class with read-only Item properties, no element names, and reference comparison under ==.

open as a page

In C#, why does `long total = (long)value;` throw InvalidCastException when the `object value` holds a boxed int?

level: middleimportance: must knowfreq 60%

basics

~20 s

Casting object to long is an unboxing conversion, and unboxing succeeds only for the exact value type that was boxed. The box holds an Int32, so the runtime throws InvalidCastException; unbox to int first, then widen: (long)(int)value.

open as a page

In C#, why do two equal items both stay in a HashSet<T> when their class overrides Equals but not GetHashCode, and what is the fix?

level: middleimportance: must knowfreq 78%

basics

~20 s

HashSet<T> compares stored hash codes before it calls Equals, and the inherited Object.GetHashCode gives each object its own hash, so equal items rarely meet. Override GetHashCode over the same fields Equals uses, typically with HashCode.Combine.

open as a page

Why does C# reject `shelf[i].X = 5` with CS1612 when `shelf` is a `List<Point>` of structs, yet accept it on a `Point[]` array?

level: middleimportance: must knowfreq 70%

basics

~20 s

The List<T> indexer getter returns a copy of the struct, and assigning a field of that temporary copy could never reach the list, so the compiler reports CS1612. An array element is a variable, so the assignment edits it in place.

open as a page

In C#, why does (a, b) = (b, a) swap two variables correctly when a = b; b = a; does not?

level: juniorimportance: should knowfreq 50%

basics

~10 s

(a, b) = (b, a) is a deconstructing assignment: C# reads both right-hand values before writing either target, so neither old value is lost. The two-statement version overwrites a before reading it back.

open as a page

In C#, a mutable Counter struct is assigned to an IIncrement interface variable; why does calling Increment through that variable leave the struct unchanged?

level: middleimportance: should knowfreq 45%

basics

~20 s

Converting a struct to an interface type boxes it, so the interface variable refers to a heap copy. Increment mutates that boxed copy; the original local never changes, and casting the box back to Counter yields yet another copy.

open as a page

Why should a C# struct used as a Dictionary key implement IEquatable<T>, and what must its Equals(object) and GetHashCode do alongside it?

level: middleimportance: should knowfreq 55%

basics

~10 s

EqualityComparer<T>.Default uses IEquatable<T>.Equals(T) when the struct implements it; otherwise it calls Equals(object), which boxes the key on every comparison. Equals(object) must forward to Equals(T), and GetHashCode must hash the same fields.

open as a page

When you overload operator == on a C# class, what does the compiler require, and why can a null check inside it overflow the stack?

level: middleimportance: should knowfreq 45%

basics

~20 s

C# requires operator != beside operator == (error CS0216) and warns if Equals or GetHashCode is not overridden. Writing left == null inside the operator calls the same operator again, recursing until the stack overflows; use is null instead.

open as a page

In C#, is it true that value types live on the stack, and where does a struct field or a struct array element actually live?

level: middleimportance: should knowfreq 60%

basics

~20 s

Only as a simplification. A value lives wherever its variable lives: a struct local usually sits on the stack or in registers, but a struct field of a class or a struct array element is stored inline inside that heap object.

open as a page

In C#, why does calling a mutating method on each struct element inside a foreach loop over an array leave the array unchanged?

level: middleimportance: should knowfreq 58%

basics

~20 s

The foreach iteration variable holds a copy of each struct element, so a mutating method changes only that copy. Assigning one of its fields fails with CS1654; to change the elements, index the array in a for loop.

open as a page

How do you make a C# Point class support var (x, y) = point, and which rules does the compiler apply to Deconstruct?

level: middleimportance: should knowfreq 50%

basics

~20 s

Declare a void Deconstruct method with one out parameter per component, as an instance or extension method. The compiler calls it for var (x, y) = point and foreach (var (x, y) in points), choosing the overload by out-parameter count.

open as a page

A C# method returns (decimal Net, decimal Tax); why does assigning it to (decimal Tax, decimal Net) silently swap the values?

level: middleimportance: should knowfreq 40%

basics

~10 s

C# tuple element names are compile-time aliases for Item1 and Item2. Converting one tuple type to another matches elements by position, so the target's Tax receives the net amount, with no diagnostic.

open as a page

In C#, how does == compare two value tuples, and when can it disagree with ValueTuple.Equals?

level: middleimportance: should knowfreq 45%

basics

~10 s

Since C# 7.3 the compiler rewrites tuple == into element-by-element == comparisons, ignoring names. Equals uses EqualityComparer<T>.Default per element instead, so NaN or object-typed elements can make the two disagree.

open as a page

In C#, why does a generic method constrained with `where T : IComparable<T>` call CompareTo on an int without boxing, while an `IComparable<int>` parameter boxes it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Inside the generic method the compiler emits a constrained call on the T value itself, and for an int the JIT turns it into a direct call to Int32.CompareTo. An IComparable<int> parameter is a reference, so the int must be boxed to pass it.

open as a page

An allocation profile of a C# service shows Int32 boxes from a metrics logger with object parameters and a legacy ArrayList; where else does boxing hide, and how do you remove it?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Boxing hides wherever a value type meets an object or interface signature: ArrayList and Hashtable, object parameters, string.Format arguments, and ToString or GetHashCode on a struct that does not override them. Generic, typed APIs remove it.

open as a page

In C#, why does an Equals override written with `obj is LineItem` break symmetry once GiftLineItem derives from it, and what does a GetType() check change?

level: seniorimportance: should knowfreq 40%

basics

~20 s

An is LineItem test accepts any subclass, so a plain item can equal a gift item while the gift's own Equals rejects the plain one. Comparing GetType() in the base Equals makes objects of different run-time types unequal, restoring symmetry.

open as a page

A C# Dictionary<Sku, int> stops finding an entry after code changes a property on the Sku key object — why, and how do you prevent it?

level: seniorimportance: should knowfreq 60%

basics

~20 s

Dictionary<TKey,TValue> stores each key's hash code when it is added and files the entry under that hash. Mutating a field that feeds GetHashCode leaves the entry under the old hash, so lookups and Remove miss it; make key members immutable.

open as a page

In C#, `shelf[i].MoveBy(1, 0)` on a `List<Point>` of mutable structs compiles without a warning, yet the item never moves; why, and how do you fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

The List<T> indexer returns a copy of the struct, and C# lets a method run on that temporary copy, so MoveBy changes the copy and the copy is discarded. Write the copy back, use an array, or make the struct immutable.

open as a page

In C#, why can calling a method on a large struct held in a readonly field or received as an in parameter copy the whole struct on every call?

level: seniorimportance: should knowfreq 48%

basics

~20 s

A readonly field or in parameter must not change, but a struct member not marked readonly may write to this, so the compiler runs it on a hidden copy. Declaring the struct or its members readonly removes the copy.

open as a page

In C# 10 and later, why do default(T) and new T[n] skip a struct's parameterless constructor and its field initializers?

level: seniorimportance: should knowfreq 42%

basics

~20 s

default(T) and array creation yield zero-filled memory without running any code. A struct's parameterless constructor, and the field initializers it executes, run only when that constructor is declared and the value is created with new S() or a generic new T().

open as a page

In C#, what do a struct's inherited ValueType.Equals and GetHashCode do, and why are they costly for a struct used as a dictionary key?

level: seniorimportance: should knowfreq 50%

basics

~20 s

ValueType.Equals compares raw bytes only for structs without reference or floating-point fields; otherwise it reads every field through reflection, boxing as it goes. ValueType.GetHashCode then hashes only the first field, so keys differing elsewhere collide.

open as a page

As a lead, what rule would you set for when a type in a C# codebase may be a struct, and how would you enforce it?

level: principalimportance: should knowfreq 28%

basics

~20 s

Default to classes; allow a struct for a small, single-value type that is declared readonly, valid when zeroed, defines its equality and is rarely boxed. Require measurements for large or mutable structs, and enforce the rule with analyzers and review.

open as a page

A C# pricing service returns (decimal Net, decimal Tax), yet System.Text.Json serializes the result as {}; why, and what is the fix?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

A C# tuple is a ValueTuple whose elements are fields named Item1 and Item2, and System.Text.Json skips fields by default. Net and Tax exist only in compiler metadata, so return a named record or class instead.

open as a page