0
0
CsharpConceptBeginner · 3 min read

What is readonly struct in C# and How It Works

A readonly struct in C# is a special kind of structure that guarantees its data cannot be changed after creation. It helps improve performance by avoiding unnecessary copies and signals that the struct is immutable.
⚙️

How It Works

A readonly struct is like a sealed box that you can look inside but cannot change what’s inside once it’s closed. When you mark a struct as readonly, you tell the compiler that none of its fields can be modified after the struct is created.

This means any method inside the struct cannot change its data, and the compiler can optimize how it handles the struct to avoid making extra copies. Think of it like a recipe card that you can read many times but never erase or rewrite.

Because structs are value types and usually copied when passed around, marking them as readonly helps reduce the cost of copying by allowing the compiler to pass references safely when it knows the data won’t change.

💻

Example

This example shows a readonly struct representing a 2D point. Its fields cannot be changed after creation, ensuring immutability.

csharp
public readonly struct Point
{
    public int X { get; }
    public int Y { get; }

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

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

class Program
{
    static void Main()
    {
        Point p = new Point(3, 4);
        System.Console.WriteLine(p);
        // p.X = 5; // This line would cause a compile error because the struct is readonly
    }
}
Output
(3, 4)
🎯

When to Use

Use readonly struct when you want to create small, immutable data types that represent values which should not change after creation. This is common for things like points, colors, or other simple data containers.

It is especially useful when you want to improve performance by avoiding unnecessary copying of structs in your program. Marking a struct as readonly also makes your code safer by preventing accidental changes to data.

For example, in graphics programming, a readonly struct can represent a pixel color that never changes, or in financial apps, an immutable money value.

Key Points

  • Readonly structs guarantee immutability of their fields.
  • They help the compiler optimize by avoiding copies.
  • Methods inside cannot modify the struct’s data.
  • Useful for small, value-type data that should not change.
  • Trying to modify fields causes compile-time errors.

Key Takeaways

A readonly struct is an immutable value type that cannot change after creation.
It improves performance by allowing the compiler to avoid unnecessary copying.
Use readonly structs for small data containers that represent fixed values.
Modifying fields inside a readonly struct causes compile errors.
Readonly structs make your code safer and clearer about immutability.