What is the readonly member in C#?

Overview

The readonly keyword in C# is typically used with members of a struct. Using readonly with a struct member restricts the change of state of that member (in the case that the member itself is a variable) or restricts the change of state of any other members (in the case that the member is a function).

Examples

The following code shows an example in which using readonly raises an error:

struct A {
private int x;
public readonly void changeX() {
x = 10;
}
}
class HelloWorld {
static void Main() {
A a;
a.changeX();
}
}

In the example above, the changeX method of the struct A assigns 10 to the member x. Since this is a change of state operation, readonly cannot be used with the changeX method.

The following is another example of using readonly with a member function of a struct:

struct A {
private int[] x;
public A(int len) {
x = new int[len];
}
private int[] getX() { return x; }
public readonly int getLenOfX() {
return getX().Length;
}
}
class HelloWorld {
static void Main() {
A a = new A(5);
System.Console.WriteLine(a.getLenOfX());
}
}

Output:

5

In the example above, the getLenOfX method in struct A is a readonly member. The getLenOfX method calls the getX method to fetch the integer array stored in the member variable x and returns the length of the array.

The getX method is not a readonly method, so the compiler is not sure whether getX will modify the state of any member of struct A. Therefore, the compiler creates a temporary copy of struct A (called a hidden copy), calls the getX method on that hidden copy, and returns the length.

Another use of the readonly keyword is as follows:

struct A {
public readonly int x;
public A(int valX) {
x = valX;
}
}
class HelloWorld {
static void Main() {
A a = new A(10);
System.Console.WriteLine(a.x);
a.x = 100;
System.Console.WriteLine(a.x);
}
}

In the example above, the member variable x of struct A is specified as readonly. The code tries to change the value of x in line 4 (inside the constructor) and in line 12 (inside the Main method). However, the error raised is only for line 12. This is because the readonly member variables are allowed to be initialized in the constructor; however, their value after that cannot be changed.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved