Picture the shipping page of a Portland, Oregon, coffee roaster. Every bag ships in a carton, and each carton is just three numbers: length, width and height in inches.
That’s the job of a struct in C#: a small value type that copies its data on assignment instead of sharing a reference. We’ll build that Dimensions type on .NET 10, from a plain struct to a readonly record struct.
Here’s what we’re building. Two cartons, a copy, an equality check and the type’s real size:

Before You Start the Struct Build
You need the .NET 10 SDK and VS Code; each step runs with dotnet run File.cs. You already use structs: the data types in C# like int and bool are structs. Our two cartons:
| Carton | Length | Width | Height | Volume |
|---|---|---|---|---|
| Small (one 12 oz bag) | 12 in | 9 in | 4 in | 432 cu in |
| Tall (stacked bags) | 12 in | 9 in | 16 in | 1,728 cu in |
Step 1: Declare a Struct with Fields, a Constructor and a Method
Use the struct keyword where you’d normally write class. A struct can hold fields, properties, constructors and methods, just like a class:
Dimensions box = new Dimensions(12, 9, 4);
Console.WriteLine($"{box.Length} x {box.Width} x {box.Height} in");
Console.WriteLine($"Volume: {box.Volume()} cu in");
struct Dimensions
{
public int Length;
public int Width;
public int Height;
public Dimensions(int length, int width, int height)
=> (Length, Width, Height) = (length, width, height);
public int Volume() => Length * Width * Height;
}
Output:
12 x 9 x 4 in
Volume: 432 cu in

A struct constructor must leave every field assigned. My constructor in C# guide covers overloading and chaining.
Checkpoint: 12 x 9 x 4 in and Volume: 432 cu in.
Step 2: See Struct Value Semantics (Copy on Assignment)
This is the difference that bites people. A struct variable in C# holds the data itself, so run the same lines against a struct and a class:
var boxA = new BoxStruct { Height = 4 };
var boxB = boxA; // copies the whole value
boxB.Height = 16;
Console.WriteLine($"struct: A = {boxA.Height}, B = {boxB.Height}");
var refA = new BoxClass { Height = 4 };
var refB = refA; // copies the reference
refB.Height = 16;
Console.WriteLine($"class: A = {refA.Height}, B = {refB.Height}");
struct BoxStruct { public int Height; }
class BoxClass { public int Height; }
Output:
struct: A = 4, B = 16
class: A = 16, B = 16

boxB = boxA copied the data, so A kept 4; the class copied a reference to one object. Passing a struct to a method copies it the same way unless you add ref.
Checkpoint: struct: A = 4, B = 16 and class: A = 16, B = 16.
Step 3: Add a Parameterless Constructor and Field Initializers (C# 10+)
Since C# 10 a struct can declare its own parameterless constructor and field initializers. Here Package defaults to UPS Ground and 1 lb. But watch what default does:
var viaNew = new Package();
var viaDefault = default(Package);
var inArray = new Package[1];
Console.WriteLine($"new Package(): {viaNew}");
Console.WriteLine($"default(Package): {viaDefault}");
Console.WriteLine($"new Package[1][0]: {inArray[0]}");
struct Package
{
public string Carrier = "UPS Ground"; // field initializer
public int Pounds { get; set; }
public Package() => Pounds = 1; // C# 10+
public override string ToString() =>
$"{Carrier ?? "(null)"}, {Pounds} lb";
}
Output:
new Package(): UPS Ground, 1 lb
default(Package): (null), 0 lb
new Package[1][0]: (null), 0 lb

default(Package) and new arrays skip your constructor and zero every field. Important: make all-zero a valid state, or check for null values like that empty Carrier.
Checkpoint: UPS Ground, 1 lb once, then (null), 0 lb twice.
Step 4: Make the Struct Immutable and Comparable (readonly record struct)
Microsoft recommends immutable structs, since silent copies make mutable ones confusing. A readonly struct needs readonly fields and get-only or init properties, good encapsulation in C#.
Equality is the other gap. Every struct inherits ValueType.Equals, but not == or IEquatable. A readonly record struct generates all of it, plus ToString():
var a = new Plain(12, 9, 4);
var b = new Plain(12, 9, 4);
Console.WriteLine($"Plain Equals: {a.Equals(b)}");
Console.WriteLine($"Plain IEquatable: {Is<Plain>()}");
var c = new Dimensions(12, 9, 4);
var d = new Dimensions(12, 9, 4);
Console.WriteLine($"Record ==: {c == d}");
Console.WriteLine($"Record IEquatable: {Is<Dimensions>()}");
Console.WriteLine($"Record ToString: {c}");
static bool Is<T>() => typeof(IEquatable<T>).IsAssignableFrom(typeof(T));
struct Plain(int l, int w, int h)
{
public int L = l, W = w, H = h;
}
readonly record struct Dimensions(int Length, int Width, int Height);
Output:
Plain Equals: True
Plain IEquatable: False
Record ==: True
Record IEquatable: True
Record ToString: Dimensions { Length = 12, Width = 9, Height = 4 }

ValueType.Equals(object) boxes the argument and can fall back to reflection. For dictionary keys, implement IEquatable or let record struct do it.
Checkpoint: Plain IEquatable: False and Record IEquatable: True.
Step 5: Implement an Interface on the Struct (Boxing)
A struct can’t inherit from a class or another struct, but it can implement any interface in C#. Converting it to that interface boxes it, which means another copy:
var carton = new Carton(4);
IResizable asInterface = carton; // boxing: a copy on the heap
asInterface.Grow(2);
Console.WriteLine($"carton: {carton.Height}, boxed: {asInterface.Height}");
object asObject = carton; // boxed again
Console.WriteLine($"asObject is Carton: {asObject is Carton}");
interface IResizable
{
int Height { get; }
void Grow(int inches);
}
struct Carton(int height) : IResizable
{
public int Height { get; private set; } = height;
public void Grow(int inches) => Height += inches;
}
Output:
carton: 4, boxed: 6
asObject is Carton: True

Grow(2) changed the boxed copy on the heap, not carton. I explain the cost of that heap copy in boxing and unboxing in C#.
Checkpoint: carton: 4, boxed: 6 and asObject is Carton: True.
Test the Finished Struct in C#
Here’s the program from the screenshot at the top. A with expression (any struct, C# 10+) copies the small carton with only Height changed:
using System.Runtime.CompilerServices;
var small = new Dimensions(12, 9, 4);
var tall = small with { Height = 16 };
Dimensions copy = small;
Console.WriteLine($"Small box: {small}");
Console.WriteLine($"Tall box: {tall}");
Console.WriteLine($"copy == small: {copy == small}");
Console.WriteLine($"Size: {Unsafe.SizeOf<Dimensions>()} bytes");
readonly record struct Dimensions(int Length, int Width, int Height)
{
public int Volume => Length * Width * Height;
public override string ToString() =>
$"{Length} x {Width} x {Height} in, {Volume} cu in";
}
Output:
Small box: 12 x 9 x 4 in, 432 cu in
Tall box: 12 x 9 x 16 in, 1728 cu in
copy == small: True
Size: 12 bytes
Unsafe.SizeOf reports 12 bytes, three 4-byte int values. Without the override you’d get the record’s own ToString() in C#.
When Should You Use a Struct Instead of a Class?
Microsoft’s Framework Design Guidelines say to consider a struct when instances are small and short-lived or embedded in other objects. They say to avoid one unless the type has all four traits below:
| Guideline trait | Dimensions | A Customer type |
|---|---|---|
| Represents a single value (like int) | Yes, one carton size | No, many related facts |
| Instance size under 16 bytes | Yes, 12 bytes | No, strings plus history |
| Immutable | Yes, readonly | Usually changes |
| Can inherit / be inherited | No | Yes, see inheritance in C# |
Anything else should be a class. To return a few values, a tuple in C# is lighter; for named options, use an enum in C#.
ref struct Basics: Span and Stack-Only Types
A ref struct lives only on the stack; Span is one. Write your own when a type must hold a span:
Span<int> heights = stackalloc int[] { 4, 6, 16 }; // stack memory
var ruler = new Ruler(heights);
Console.WriteLine($"Tallest: {ruler.Max()} in");
ref struct Ruler(Span<int> data) // only a ref struct can hold a Span
{
private Span<int> _data = data;
public int Max() { int m = 0; foreach (int h in _data) m = Math.Max(m, h); return m; }
}
Output:
Tallest: 16 in
The trade-off: a ref struct can’t be a C# array element, a class field, boxed or captured in a lambda.
Troubleshooting Struct Errors in C#
The classic gotcha is a List in C#: its indexer returns a copy, so change a local and write it back. An array hands you the element itself:
List<Carton> cartons = [new(4), new(6)];
var first = cartons[0]; // the indexer returns a copy
first.Height = 16;
cartons[0] = first; // write the copy back
Console.WriteLine($"List: {cartons[0].Height}");
Carton[] shelf = [new(4)];
shelf[0].Height = 16; // an array element is the value itself
Console.WriteLine($"Array: {shelf[0].Height}");
struct Carton(int height) { public int Height = height; }
Output:
List: 16
Array: 16
Here are the errors I hit most, in one file:
var cube = new Cube(6);
cube.Side = 8; // init-only property
List<Crate> crates = [new()];
crates[0].Size = 2; // List indexer copy
bool same = new Crate() == new Crate(); // no == on a plain struct
readonly struct Cube(int side) { public int Side { get; init; } = side; }
struct Crate { public int Size; }
Build output:
C:\DotNetDemo\StructDemo\Rules.cs(2,1): error CS8852: Init-only property or indexer 'Cube.Side' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
C:\DotNetDemo\StructDemo\Rules.cs(4,1): error CS1612: Cannot modify the return value of 'List<Crate>.this[int]' because it is not a variable
C:\DotNetDemo\StructDemo\Rules.cs(5,13): error CS0019: Operator '==' cannot be applied to operands of type 'Crate' and 'Crate'
The build failed. Fix the build errors and run again.
Declaration mistakes stop the build before method bodies are checked, so they need their own file:
Console.WriteLine("This file never builds");
struct Crate : Pallet { public int Size; } // structs can't inherit
class Pallet { }
struct Weight { public int Ounces = 16; } // initializer, no constructor
Build output:
C:\DotNetDemo\StructDemo\Declarations.cs(3,16): error CS0527: Type 'Pallet' in interface list is not an interface
C:\DotNetDemo\StructDemo\Declarations.cs(5,8): error CS8983: A 'struct' with field initializers must include an explicitly declared constructor.
The build failed. Fix the build errors and run again.
The fixes: use with for CS8852, copy out and assign back for CS1612, a record struct for CS0019, an interface for CS0527, and any explicit constructor for CS8983.
Where to Take It Next
- Add a
Moneyrecord struct (adecimalamount) for the shipping rate. - Split a large struct across files as a partial struct; the keyword works on structs too.
For the object-oriented side of C# types, read these next:
- The four OOP concepts in C#, explained with examples
- Abstract classes, which structs can never derive from
- C# interview questions, struct vs class included
- Naming conventions for C# classes and structs
Frequently Asked Questions
What is a struct in C#?
A value type declared with struct. Your variable holds the data itself, so assignment and method calls copy it. Use it for small, immutable values like a size or a point.
Is a struct stored on the stack or the heap?
A local struct usually sits on the stack, a struct field sits inline in its containing object, and a boxed struct goes to the heap. Only a ref struct is guaranteed stack-only.
Can a struct have a parameterless constructor?
Yes, since C# 10, and it must be public. It runs for new T() only; default(T) and new arrays still zero every field.
Can a struct inherit from another struct or class?
No, and it can’t be a base class either. It can implement interfaces, but converting it to one boxes a copy.
What is the difference between a struct and a record struct?
A record struct generates value equality, ==, IEquatable and ToString(). Microsoft’s structure types reference lists the rest of the rules.
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…