C# Readonly

Readonly prevents fields from being changed. Readonly fields can be initialized at runtime, unlike const values. Attempts to change them later are disallowed. This C# modifier does not affect performance.

Tip:When using readonly, consider instead the const modifier. Const is better in some program contexts.

Example

In this example we use readonly to initialize a DateTime struct. We cannot set a const DateTime—this raises a compilation error. But we want to designate a DateTime field as unavailable for further changes.

Next:In this program we don't want to mistakenly reset the startup time. Using readonly prevents this.

In this example, a new class of type Manager is instantiated. Internally, the Manager class has a constructor. In the constructor, the startup time is initialized. We can assign the readonly field here.

Readonly keyword. The constructor takes the current time from the DateTime.Now property and assigns it to an unchangeable readonly DateTime field. You are not able to accidentally reassign the startup time.

Tip:The benefit here is that other code, or the code from your team members, can't change the readonly field.

And:This makes it less likely to be messed up by someone who doesn't understand its purpose.

Inline initialization

It is possible to use an inline initialization for readonly. This means that you do not need to put the starting value in a constructor explicitly. In IL Disassembler we see the compiler has put it in the constructor itself.

Benchmark

Here we look at a simple benchmark of readonly and const ints. We also include a regular instance of int in the benchmark. The readonly int and the int field had equivalent performance. The const int was faster.

Error

One mistake you might make when using readonly is trying to assign to it in a place that is not a constructor. This will result in the following ugly error when you try to compile.

Error:A readonly field cannot be assigned to (except in a constructor or a variable initializer).

ReadOnlyCollection

You cannot make a collection itself readonly with just the readonly keyword. When you make a field reference of a collection readonly, just that reference itself is readonly. The elements inside are no different.

Tip:You can use the ReadOnlyCollection type, which wraps other collections and prevents writes.

Summary

We saw a practical usage of the readonly keyword, and also noted how the first two examples are compiled into IL. Finally, we compared the performance of readonly and const in an object-oriented program.

And:Readonly and regular fields have equivalent performance, while const is somewhat faster.