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:
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.
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// constructorpublic Marvel(string name){this.CharacterName = name;// *CORRECT*}// `this` variable cannot be changed except// for constructorpublic 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// constructorpublic Marvel(string name){this.CharacterName = name;//*CORRECT*}}
Free Resources