Readonly structs help keep data safe by making sure it cannot be changed after creation.
Readonly structs in 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.
Point with two properties X and Y.readonly struct Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y)
{
X = x;
Y = y;
}
}Temperature that holds a temperature value in Celsius.readonly struct Temperature
{
public double Celsius { get; }
public Temperature(double celsius)
{
Celsius = celsius;
}
}This program creates a readonly struct Point and prints its values. Trying to change X or Y after creation will cause an error.
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 } }
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.
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.
Practice
What is the main purpose of declaring a struct as readonly in C#?
Solution
Step 1: Understand what readonly means for structs
A readonly struct means its fields cannot be changed after the struct is created.Step 2: Compare options with this meaning
Only To prevent modification of its fields after creation matches this behavior by preventing modification after creation.Final Answer:
To prevent modification of its fields after creation -> Option DQuick Check:
Readonly struct = Immutable fields [OK]
- Thinking readonly allows inheritance
- Confusing readonly with mutable structs
- Assuming readonly structs can resize dynamically
Which of the following is the correct way to declare a readonly struct in C#?
?Solution
Step 1: Recall correct syntax for readonly structs
The keywordreadonlycomes beforestructin the declaration.Step 2: Check each option's keyword order
Only readonly struct Point { public int X; public int Y; } placesreadonlybeforestructcorrectly.Final Answer:
readonly struct Point { public int X; public int Y; } -> Option AQuick Check:
Keyword order: readonly struct [OK]
- Placing readonly after struct
- Mixing order of keywords
- Using readonly as a suffix
What will be the output of the following C# code?
readonly struct Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y) { X = x; Y = y; }
}
var p = new Point(3, 4);
Console.WriteLine($"X: {p.X}, Y: {p.Y}");Solution
Step 1: Understand readonly struct with get-only properties
The struct has get-only properties set in the constructor, which is allowed.Step 2: Check the constructor and output
The constructor sets X=3 and Y=4, so printing them outputs "X: 3, Y: 4".Final Answer:
X: 3, Y: 4 -> Option AQuick Check:
Constructor sets values correctly [OK]
- Assuming readonly structs cannot have properties
- Thinking constructor cannot set properties
- Expecting runtime errors accessing properties
Identify the error in this code snippet using a readonly struct:
readonly struct Rectangle
{
public int Width;
public int Height;
public void Resize(int w, int h)
{
Width = w;
Height = h;
}
}Solution
Step 1: Understand mutability rules in readonly structs
Readonly structs cannot modify their fields inside instance methods.Step 2: Analyze the Resize method
Resize tries to assign new values to Width and Height fields, which is not allowed.Final Answer:
Cannot assign to fields inside a method of a readonly struct -> Option CQuick Check:
Readonly struct fields are immutable in methods [OK]
- Thinking methods can modify fields in readonly structs
- Assuming missing constructor causes error
- Believing readonly structs cannot have any methods
You want to create a readonly struct Circle that stores a radius and calculates area. Which of these implementations is correct and efficient?
?Solution
Step 1: Check readonly struct with immutable radius
readonly struct Circle { public double Radius { get; } public Circle(double r) => Radius = r; public double Area => Math.PI * Radius * Radius; } uses a readonly struct with a get-only property set in constructor, which is correct.Step 2: Verify area calculation and mutability
Area is a property calculated from Radius, no setters modify Radius, ensuring immutability and efficiency.Final Answer:
readonly struct Circle { public double Radius { get; } public Circle(double r) => Radius = r; public double Area => Math.PI * Radius * Radius; } -> Option BQuick Check:
Immutable radius with calculated area [OK]
- Trying to set fields in readonly struct after creation
- Using mutable fields in readonly structs
- Adding setters that break immutability
Ready to prove it?
Pass the test and this pattern moves unknown
