In c#, readonly is a keyword that is useful to define read-only fields in our applications. The read-only field values need to be initialized either at the declaration or in a constructor of the same class, unlike the constant keyword in c#. If we use
readonly keyword with fields, then those field values will be evaluated at the runtime.
To define read-only fields in c#, we need to use
readonly keyword during the declaration of fields in our application, and we can use
readonly modifier with the numbers, boolean values, strings, or with null references.
In c#, if we use
readonly keyword to define the read-only field, then that field value cannot be changed once the constructor execution has finished, so we should not use
readonly keyword with the fields whose value will be changed at any time.
It’s mandatory to initialize read-only field values either at the declaration or in a constructor; otherwise, we will get compile-time errors in our c# application.
Following is the syntax of defining read-only fields using
readonly keyword in c# programming language.
If you observe the above syntax, we used a
readonly keyword to declare a read-only variable in our application.
The following are the different ways of declaring and initializing read-only fields in the c# programming language.
If we uncomment the commented code in SetDetails() method, then we will get compile errors because, in c#, the read-only field values can be initialized either during declaration or in a constructor.
Following is the example of defining and using read-only fields in c# programming language with
If you observe the above example, we created read-only fields with different data types, and if we uncomment the commented code, we will get a compile-time error because we are trying to change the value of read-only fields.
As discussed, once the read-only field is declared and initialized, then that field value must be the same throughout the application.
When you run the above c# program, you will get the result as shown below.
The following are the important features of the read-only variables in the c# programming language.
The following are the difference between constant and readonly properties in the c# programming language.
constkeyword and read-only fields can be created by using
This is how we can create and use read-only fields in our c# programming language with
readonly keyword based on our requirements.