ZetCode

C# struct

last modified October 18, 2026

In this article we work with the struct type in C#.

The struct type

A structure is a value type. It is defined with the struct keyword. Structures are similar to classes, but they are meant to represent small, lightweight data such as a point, a rectangle, or a color. Primitive types like int, bool, and float are structures too.

The key difference is the copy semantics. Assigning a structure, or passing it to a method, copies the whole value. Assigning a class instance copies only the reference. A structure therefore has no identity and cannot be shared by accident.

Structures are often said to live "on the stack", but this is a simplification. A local variable of a struct type is typically stored on the stack (or in a register), but a structure that is a field of a class, an element of an array, or a boxed value lives on the heap, inside the object that contains it. What matters is that a structure has no object header of its own and is not tracked separately by the garbage collector. For small values, this saves allocations and memory.

All structures derive from System.ValueType and then from System.Object. They are implicitly sealed, so they do not support inheritance, and members cannot be protected or virtual. A structure can implement interfaces, and can override ToString, Equals, and GetHashCode.

A structure can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types. Since C# 10, it can also declare a parameterless constructor. Every structure has a default value, with all fields set to zero or null, available through default(T) and through array allocation, whether or not a constructor exists.

Microsoft's guideline is to prefer a structure for types that are small (about 16 bytes or less), short-lived or embedded in other objects, logically represent a single value, and are immutable.

C# struct simple example

The following example creates a simple structure.

Program.cs
var p = new Point(2, 5);
Console.WriteLine(p);

public struct Point
{
    private int x;
    private int y;

    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public override string ToString() => $"Point x:{x}, y:{y}";
}

The example creates a Point structure. The point could be a class too, but a structure avoids a heap allocation for every point, which matters when we deal with lots of them.

var p = new Point(2, 5);
Console.WriteLine(p);

We create the Point structure and print it. The Console.WriteLine method calls the ToString method.

public override string ToString() => $"Point x:{x}, y:{y}";

Inheritance is not supported for structures, but they can still override the methods of System.Object, from which they implicitly inherit.

$ dotnet run
Point x:2, y:5

The new keyword and default values

A structure variable can be used without the new keyword, provided that all its fields are assigned before the first read.

Program.cs
Person p;
p.name = "Jane";
p.age = 17;

Console.WriteLine($"{p.name} is {p.age} years old");

var q = new Person();
Console.WriteLine($"[{q.name}] {q.age}");

var d = default(Person);
Console.WriteLine(d.age);

Person[] people = new Person[3];
Console.WriteLine(people[0].name is null);

public struct Person
{
    public string name;
    public int age;
}

We have a Person structure with two public fields.

Person p;
p.name = "Jane";
p.age = 17;

We declare the variable and then assign every field. If we left one out and tried to read p as a whole, the compiler would report an unassigned variable. This works with fields only; structures with properties need new.

var q = new Person();
var d = default(Person);
Person[] people = new Person[3];

These three forms all produce a structure whose fields are zero or null. The array elements are valid structure values; unlike an array of class instances, there are no null elements to guard against.

$ dotnet run
Jane is 17 years old
[] 0
0
True

C# struct constructors and properties

Structures can use auto-implemented properties and can have several constructors, including a parameterless one.

Program.cs
var p1 = new Person("John Doe", "gardener");
Console.WriteLine(p1);

var p2 = new Person("Roger Roe", "driver");
Console.WriteLine(p2);

var p3 = new Person();
Console.WriteLine(p3);

public struct Person
{
    public Person(string name, string occupation)
    {
        Name = name;
        Occupation = occupation;
    }

    public Person()
    {
        Name = "unknown";
        Occupation = "unknown";
    }

    public string Name { get; set; }
    public string Occupation { get; set; }

    public override string ToString() => $"{Name} is a(n) {Occupation}";
}

In the program, we have a Person structure with auto-implemented Name and Occupation properties.

public Person()
{
    Name = "unknown";
    Occupation = "unknown";
}

A parameterless constructor lets us set non-default initial values. Since C# 11, the compiler assigns the fields we omit with their default values automatically; before that, every field had to be assigned in a constructor. Keep in mind that the constructor runs only for new Person(); default(Person) and array elements bypass it.

$ dotnet run
John Doe is a(n) gardener
Roger Roe is a(n) driver
unknown is a(n) unknown

C# readonly struct

With the readonly modifier, we create an immutable structure. All its fields must be readonly, and all its properties must be read-only or init-only. The compiler can then skip the defensive copies it otherwise makes when a structure is accessed through a read-only reference, which improves performance.

Program.cs
var p = new Point(3, 7);
Console.WriteLine(p);

var q = p with { X = 10 };
Console.WriteLine(q);
Console.WriteLine(p);

// p.X = 5;   // error CS8852: Init-only property can only be assigned in an object initializer

public readonly struct Point
{
    public Point(double x, double y)
    {
        X = x;
        Y = y;
    }

    public double X { get; init; }
    public double Y { get; init; }

    public double DistanceTo(Point other) => Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2));

    public override string ToString() => $"({X}, {Y})";
}

In the example, we create a point and derive a modified copy from it.

public double X { get; init; }
public double Y { get; init; }

The init keyword creates an init-only setter. It permits assigning a value only during construction or in an object initializer. The commented-out line p.X = 5 would be a compile error (CS8852).

var q = p with { X = 10 };

The with expression creates a copy of the structure with the given properties changed. The original is untouched, which is the usual way to "modify" an immutable value.

$ dotnet run
(3, 7)
(10, 7)
(3, 7)

C# structures are value types

When a value type is assigned, the value is copied. After the assignment the two variables are independent.

Program.cs
var p1 = new Person("Beky", 18);
var p2 = p1;

Console.WriteLine(p2);
p2.Name = "Jane";
p2.Age = 17;

Console.WriteLine(p2);
Console.WriteLine(p1);

public struct Person(string name, int age)
{
    public string Name { get; set; } = name;
    public int Age { get; set; } = age;

    public override string ToString() => $"{Name} is {Age} years old";
}

We have a Person structure with two properties, initialized from the parameters of a primary constructor.

var p1 = new Person("Beky", 18);
var p2 = p1;

Here we create a structure and assign it to another variable, which copies it.

p2.Name = "Jane";
p2.Age = 17;

We change the data of the second structure. The first one is not affected, because we work on a copy.

$ dotnet run
Beky is 18 years old
Jane is 17 years old
Beky is 18 years old

C# struct mutation pitfalls

Mutable structures are a common source of bugs, because it is easy to change a copy instead of the original. The following example shows the typical cases.

Program.cs
var s = new Counter();
s.Increment();
s.Increment();
Console.WriteLine(s.Value);

// a copy is changed when a struct is passed by value
Bump(s);
Console.WriteLine(s.Value);

// ref passes the original
BumpRef(ref s);
Console.WriteLine(s.Value);

// the list indexer returns a copy, so the call below changes a temporary value
var list = new List<Counter> { new Counter() };
list[0].Increment();
Console.WriteLine(list[0].Value);

// copy out, modify, and store back
var c = list[0];
c.Increment();
list[0] = c;
Console.WriteLine(list[0].Value);

// in an array the element is a variable, so this works
var arr = new Counter[1];
arr[0].Increment();
Console.WriteLine(arr[0].Value);

void Bump(Counter c) => c.Increment();
void BumpRef(ref Counter c) => c.Increment();

struct Counter
{
    public int Value { get; private set; }
    public void Increment() => Value++;
}

A Counter structure has a method that changes its state.

Bump(s);
Console.WriteLine(s.Value);

The method receives a copy, so the caller's counter is unchanged and still prints 2.

BumpRef(ref s);

With the ref modifier, the method works on the original, and the value becomes 3.

list[0].Increment();
Console.WriteLine(list[0].Value);

The indexer of List<T> returns a copy. The call compiles, but it modifies a temporary value, and the list still contains 0. We must copy the element out, modify it, and store it back. Elements of an array, in contrast, are variables, so arr[0].Increment() changes the array element.

$ dotnet run
2
2
3
0
1
1

The best defense is to make structures immutable.

C# record struct

Since C# 10, record struct generates value-based equality, ToString, deconstruction, and support for with expressions. A readonly record struct is the shortest way to declare an immutable value type.

Program.cs
var a = new Point(1, 2);
var b = new Point(1, 2);

Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b));
Console.WriteLine(a);

var c = a with { X = 5 };
Console.WriteLine(c);

var (x, y) = c;
Console.WriteLine($"{x} {y}");

var set = new HashSet<Point> { a, b, c };
Console.WriteLine(set.Count);

public readonly record struct Point(int X, int Y);

We declare a Point in one line.

public readonly record struct Point(int X, int Y);

The positional syntax creates two init-only properties and a constructor. The compiler implements Equals, GetHashCode, the == and != operators, and a ToString that prints the property values.

var (x, y) = c;

The generated Deconstruct method lets us unpack the values. The set contains two points, because a and b are equal.

$ dotnet run
True
True
Point { X = 1, Y = 2 }
Point { X = 5, Y = 2 }
5 2
2

Without the record keyword, a plain structure gets a default ValueType.Equals, which may fall back to slow reflection-based comparison, and the == operator is not available at all. Override Equals and implement IEquatable<T>, or use a record struct.

C# struct size, boxing, and in parameters

A structure copies its entire content, so large structures are expensive to pass around. Converting a structure to object or to an interface it implements boxes it: the value is copied to a new object on the heap.

Program.cs
using System.Runtime.CompilerServices;

Console.WriteLine(Unsafe.SizeOf<Point>());
Console.WriteLine(Unsafe.SizeOf<Rgb>());

object boxed = new Point(1, 2);       // boxing: copies the struct to the heap
Point unboxed = (Point)boxed;
Console.WriteLine(unboxed);

IShape shape = new Square(4);         // also boxing
Console.WriteLine(shape.Area());

Console.WriteLine(Sum(new Point(3, 4)));

static int Sum(in Point p) => p.X + p.Y;      // `in` passes a read-only reference, no copy

public readonly record struct Point(int X, int Y);
public readonly record struct Rgb(byte R, byte G, byte B);

interface IShape { double Area(); }
readonly struct Square(double side) : IShape
{
    public double Area() => side * side;
}

The example measures structures and shows boxing.

Console.WriteLine(Unsafe.SizeOf<Point>());
Console.WriteLine(Unsafe.SizeOf<Rgb>());

Unsafe.SizeOf returns the size of the value in bytes. The point has two 4-byte integers; the color has three single bytes.

object boxed = new Point(1, 2);
Point unboxed = (Point)boxed;

Assigning to object allocates a box; the cast back copies the value out again. Boxing in hot code paths causes garbage and should be avoided, for example by using generics instead of object.

static int Sum(in Point p) => p.X + p.Y;

The in modifier passes the argument by read-only reference, so even a big structure is not copied. It works best with readonly struct types.

$ dotnet run
8
3
Point { X = 1, Y = 2 }
16
7

C# nullable structures

A structure cannot be null, but Nullable<T>, written T?, adds an extra flag that allows it.

Program.cs
int? n = null;
Console.WriteLine(n.HasValue);

n = 5;
Console.WriteLine(n);

Point? p = null;
Console.WriteLine(p is null);

p = new Point(1, 2);
Console.WriteLine(p.Value.X);

Console.WriteLine(typeof(int?) == typeof(Nullable<int>));

struct Point(int x, int y)
{
    public int X { get; } = x;
    public int Y { get; } = y;
}

We use a nullable int and a nullable user-defined structure.

Point? p = null;
p = new Point(1, 2);
Console.WriteLine(p.Value.X);

Point? is shorthand for Nullable<Point>. We access the wrapped structure through the Value property, which throws if there is none.

$ dotnet run
False
5
True
1
True

C# ref struct

A ref struct must always live on the stack. It cannot be boxed, be a field of a class, be captured by a lambda, or be used across an await. Span<T> is the best-known example; it is a ref struct that points to a part of an array or other memory.

Program.cs
int[] data = [1, 2, 3, 4, 5, 6];

var window = new Window(data.AsSpan(1, 3));
Console.WriteLine(window.Sum());

ref struct Window
{
    private readonly Span<int> items;

    public Window(Span<int> items) => this.items = items;

    public int Sum()
    {
        int s = 0;

        foreach (var i in items)
        {
            s += i;
        }

        return s;
    }
}

The Window structure wraps a span over the middle of an array.

$ dotnet run
9

The sum covers 2, 3, and 4. The span refers to the original array without copying it.

Primitive types are structures

The primitive types such as int, float, and bool are structures. The C# keywords are aliases for types in the System namespace.

Program.cs
float x = 12.3f;
int y = 34;
bool z = false;

Console.WriteLine(x.GetType());
Console.WriteLine(y.GetType());
Console.WriteLine(z.GetType());

Console.WriteLine(typeof(int).IsValueType);
Console.WriteLine(typeof(string).IsValueType);

We have three variables of different types and call the GetType method on each.

Console.WriteLine(typeof(int).IsValueType);
Console.WriteLine(typeof(string).IsValueType);

The IsValueType property tells whether a type is a value type. string is a class, so it prints False.

$ dotnet run
System.Single
System.Int32
System.Boolean
True
False

Source

Structure types - language reference

In this article we covered the struct type in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.