What are readonly structs in C#?

Share

The readonly keyword is a C# modifier used to limit access to all the data members of a struct. If the readonly modifier is used in the declaration of a struct, then:

  1. The members of the struct are read-only.
  2. None of the members can have setters.
  3. A parameterized constructor is used to initialize the data members.
  4. The struct is immutable.
  5. The this variable cannot be changed in any other method except the constructor.

Remember: this is a reference to the current object in a class/struct.

svg viewer

Code

When you try to run the code below, a few errors will pop-up.

Rememeber to use a C# version that’s 7.2 or above.

public readonly struct Marvel
{
// You can have getter methods but not setter methods.
public string CharacterName { get;set; }//*ERROR*
// `this` variable can be changed in
// constructor
public Marvel(string name)
{
this.CharacterName = name;// *CORRECT*
}
// `this` variable cannot be changed except
// for constructor
public void SwitchCharacter(Marvel M)
{
this.CharacterName = M.CharacterName;// *ERROR*
}
}

Take a look below for the correct implementation of the code above:

public readonly struct Marvel
{
// No setter method included.
public string CharacterName { get; }//*Correct*
// `this` variable can be changed in
// constructor
public Marvel(string name)
{
this.CharacterName = name;//*CORRECT*
}
}
Copyright ©2024 Educative, Inc. All rights reserved