0
0
C Sharp (C#)programming~5 mins

Readonly structs in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Readonly structs help keep data safe by making sure it cannot be changed after creation.

When you want to create small data containers that should not change.
When you want to avoid accidental changes to data in your program.
When you want to improve performance by avoiding unnecessary copying.
When you want to clearly show that a struct is meant to be immutable.
Syntax
C Sharp (C#)
readonly struct StructName
{
    public int Property { get; }

    public StructName(int value)
    {
        Property = value;
    }
}

The readonly keyword before struct makes all fields readonly by default and enforces that the struct is immutable.

You can only set properties inside the constructor.

Examples
This defines a readonly struct Point with two properties X and Y.
C Sharp (C#)
readonly struct Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }
}
A readonly struct Temperature that holds a temperature value in Celsius.
C Sharp (C#)
readonly struct Temperature
{
    public double Celsius { get; }

    public Temperature(double celsius)
    {
        Celsius = celsius;
    }
}
Sample Program

This program creates a readonly struct Point and prints its values. Trying to change X or Y after creation will cause an error.

C Sharp (C#)
using System;

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() => $"Point(X={X}, Y={Y})";
}

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

Readonly structs improve safety by preventing changes after creation.

They can help the compiler optimize your code better.

Trying to modify a readonly struct's property outside the constructor will cause a compile-time error.

Summary

Readonly structs are structs that cannot be changed after they are created.

Use them to make your data safer and clearer.

They help avoid bugs caused by accidental changes.