C# / .NET Compendium PLEN
.NET / C# / C# — language fundamentals

struct in C#

The fundamental difference - value type vs reference type

This is the most important thing to understand - a struct is a value type, as opposed to a class, which is a reference type.

public struct Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class PointClass
{
    public int X { get; set; }
    public int Y { get; set; }
}

Where they live in memory - stack vs heap

Point p1 = new Point { X = 1, Y = 2 }; // lives on the STACK (usually, see below for exceptions)
PointClass c1 = new PointClass { X = 1, Y = 2 }; // c1 to referencja NA STOSIE, obiekt NA STERCIE

Struct - the data is stored directly where the variable is declared (on the stack if it is a local variable; inside the object if it is a class field).

Class - the variable is a reference (a pointer) to an object living on the heap; the reference itself is small (like a pointer), but the real data is elsewhere.

The key consequence - copying by value

public struct Point { public int X { get; set; } public int Y { get; set; } }

Point p1 = new Point { X = 1, Y = 2 };
Point p2 = p1; // COPIES the whole structure - p2 is an INDEPENDENT copy

p2.X = 100;

Console.WriteLine(p1.X); // 1 - p1 has NOT changed!
Console.WriteLine(p2.X); // 100
public class PointClass { public int X { get; set; } public int Y { get; set; } }

PointClass c1 = new PointClass { X = 1, Y = 2 };
PointClass c2 = c1; // COPIES only the REFERENCE - c1 and c2 point to the SAME object

c2.X = 100;

Console.WriteLine(c1.X); // 100 - c1 has changed TOO! It is the same object
Console.WriteLine(c2.X); // 100

This is a fundamental difference to remember - assigning a struct copies the whole object, assigning a class copies only the reference.

The same applies to passing to methods

void ModifyStruct(Point p) { p.X = 999; } // receives a COPY

var point = new Point { X = 1 };
ModifyStruct(point);
Console.WriteLine(point.X); // 1 - the original is unchanged, the method got a copy

void ModifyClass(PointClass c) { c.X = 999; } // receives a REFERENCE to the same object

var pointClass = new PointClass { X = 1 };
ModifyClass(pointClass);
Console.WriteLine(pointClass.X); // 999 - the original is CHANGED, because it is the same reference

The exception - passing by ref:

void ModifyStructByRef(ref Point p) { p.X = 999; }

var point = new Point { X = 1 };
ModifyStructByRef(ref point);
Console.WriteLine(point.X); // 999 - NOW it has changed, because we passed a reference to the structure

Built-in .NET types that are structs - you use them more often than you think

Most of the primitive types in C# are actually structs:

int, double, decimal, bool, char, DateTime, TimeSpan, Guid // WSZYSTKIE to struct!
int a = 5;
int b = a; // copying by value - exactly the same semantics as Point above
b = 10;
Console.WriteLine(a); // 5 - niezmienione

This explains why int/double/bool always behave "intuitively" (copying the value) - because they are structs, just like your own Point.

The default value - a struct can't be null (without Nullable<T>)

Point p; // ✅ OK, has a DEFAULT value (X=0, Y=0) - a struct CANNOT be "uninitialised" as null
p = null; // ❌ Compile error - a struct is not a reference, it can't be null

PointClass c; // a declaration without a value - but USING it without assignment is a compile error
c = null; // ✅ OK - a class can be null, because it is a reference

For a struct to represent "no value", you need Nullable<T> (the Point? syntax):

Point? maybePoint = null; // ✅ teraz OK - Nullable<Point>
if (maybePoint.HasValue) { var p = maybePoint.Value; }

Inheritance - a struct does NOT support it (apart from interfaces)

public struct Point : IComparable<Point> // ✅ CAN implement interfaces
{
    public int CompareTo(Point other) => 0;
}

public struct ColoredPoint : Point { } // ❌ Compile error - a struct CANNOT inherit from another struct

Every struct implicitly inherits from System.ValueType (which in turn inherits from object), and that is the end of the hierarchy - you can't inherit from it further, nor inherit from another struct yourself. This is also why record struct (which we discussed) can't have an inheritance hierarchy, unlike record class.

When to use struct - a practical rule (Microsoft Guidelines)

Microsoft recommends struct when all the following conditions are met: - It represents a single value, conceptually similar to primitives (int, DateTime) - e.g. Point, Money, Coordinates - It has a small size (recommended up to 16 bytes - larger structures lose the performance advantage when copied) - It is immutable (or at least designed with that in mind) - You don't need to "box" it to object/an interface often (see boxing below)

// A good candidate for a struct - small, a value, immutable
public readonly struct Money
{
    public decimal Amount { get; }
    public string Currency { get; }
    public Money(decimal amount, string currency) { Amount = amount; Currency = currency; }
}

readonly struct (C# 7.2+) - the compiler enforces immutability of all fields, which allows additional optimisations (the compiler knows it doesn't have to make defensive copies on every access).

Why NOT to overuse struct - the cost of copying

public struct BigStruct // BAD - too large a struct
{
    public int Field1, Field2, Field3, Field4, Field5, Field6, Field7, Field8, Field9, Field10;
    // 40 bytes - every pass to a method COPIES all 40 bytes
}

void ProcessMany(List<BigStruct> items)
{
    foreach (var item in items) // EVERY iteration copies 40 bytes of the structure
    {
        DoSomething(item); // KOLEJNA kopia przy przekazaniu do metody
    }
}

For large structures, frequent copying (when passing to methods, when iterating) becomes more expensive than using a class (where only a small reference is copied, regardless of the object's size). This is the reason for the "up to 16 bytes" limit in Microsoft's guidelines.

Boxing - the cost of using a struct as object/an interface

Point p = new Point { X = 1, Y = 2 };
object boxed = p; // BOXING - the struct is "wrapped" and copied TO THE HEAP

IComparable<Point> comparable = p; // ALSO boxing, if Point implements the interface

Boxing is an expensive operation - a struct that normally lives on the stack is copied to the heap and wrapped as a reference object, so that it can be treated as object/an interface. This is something a class never does (because it is already on the heap).

List<object> list = new List<object>();
for (int i = 0; i < 1000; i++)
{
    list.Add(i); // EVERY addition of an int (a struct) to a List<object> is BOXING - 1000 heap allocations!
}

This is also why generic collections (List<int> instead of List<object>, or List<T> in general) are so important in .NET - they avoid boxing for value types.

record struct - combining both worlds

public record struct PointDto(int X, int Y);

This is exactly a struct (memory semantics: copying by value, the stack) plus an automatically generated Equals/GetHashCode/ToString (record semantics) - the best of both, for small, immutable data.

Comparison table struct vs class

struct class
Type Value Reference
Where it lives Stack (usually) / inline in an object Heap
Assignment/passing Copies the WHOLE object Copies only the reference
Can be null No (without Nullable<T>/?) Yes
Inheritance No (interfaces only) Yes (one base class)
Default value Zero-initialised (not null) null
Cost at large size Grows (copying) Constant (copies only the reference)
Boxing when used as object/an interface Yes (expensive) No (already on the heap)
Typical use Small, immutable values (Point, Money, DateTime) Entities, services, objects with identity/behaviour

A trick question in an interview

"Can a struct have methods?" - Yes, and this is often a surprise for people who associate struct only with C/C++ (where it is a "bare" data structure without behaviour). In C# a struct can have methods, properties, constructors (but not an explicit parameterless one before C# 10 - it is always implicit, zeroing the fields), and implement interfaces - it differs from class mainly in its memory semantics (value vs reference) and the lack of inheritance, not in being unable to hold logic.


Buy me a coffee