The read-only field can be assigned a value to the read-only field in the constructor, but cannot be assigned elsewhere. The read-only field can also be an instance field rather than a static field, each instance of the class can have different values. Unlike the const field, if you want to set the field to static, it must be explicitly declared.
If you have an MDI program for editing a document, you must limit the number of documents that can be opened at the same time. Now assume that you want to sell different versions of the software, and customers can upgrade their versions to open more documents at the same time. Obviously, you cannot hard program the maximum number of documents in the source code. Instead, a field is required to indicate the maximum number of documents. This field must be read-only-read from the registry or other file storage each time the program is installed. The Code is as follows:
Public class extends enteditor
{
Public static readonly uint maxcompute ENTs;
Static plugin enteditor ()
{
MaxDocuments = DoSomethingToFindOutMaxNumber ();
}
}
In this example, the field is static, because every time you run the program instance, you only need to store the maximum number of documents once. This is why static constructor initializes it. If the read-only field is an instance field, initialize it in the instance constructor.
Public class Document
{
Public readonly DateTime CreationDate;
Public Document ()
{
CreationDate = someDate;
}
}
Note that you do not need to assign a value to a read-only field in the constructor. If no value is assigned, its value is the default value of its data type or the value initialized to it during declaration. This applies to static and instance read-only fields.