In c#, readonly is a keyword, and it 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, those field values will evaluate 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 null references.
In c#, if we use readonly
keyword to define the read-only field, that field value cannot change once the constructor execution has finished, so we should not use readonly
keyword with the fields whose value will change 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.
The above example shows that we created read-only fields with different data types and initialized field values during a constructor's declaration.
Suppose, if we uncomment the commented code in SetDetails() method, we will get compile errors because, in c#, we can initialize the read-only field values during declaration or in a constructor.
Following is the example of defining and using read-only fields in c# programming language with readonly
keyword.
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, that field value must be the same throughout the application.
When you run the above c# program, you will get the result below.
The following are the important features of the read-only variables in the c# programming language.
readonly
keyword.The following are the difference between constant and readonly properties in the c# programming language.
const
keyword and the read-only fields created by using readonly
keyword.This is how we can create and use read-only fields in our c# programming language with readonly
keyword based on our requirements.