C# Readonly Fields

Readonly keyword

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. Careful consideration of the const modifier is important.

Keywords

This C# article shows how to use the readonly keyword. Readonly prevents changes to fields.

Example

First we see an example of how you can use readonly to initialize a DateTime struct. You cannot set a const DateTime, as it raises a compilation error. However, you may need to designate a DateTime field to be unavailable for changes later on. We don't want to mistakenly reset the startup time.

Program that uses readonly [C#]

using System;

class Program
{
    static void Main()
    {
	Manager manager = new Manager();
	Console.WriteLine(manager.GetStartup());
    }
}

class Manager
{
    readonly DateTime _startup; // <-- the readonly field

    public Manager()
    {
	// Initialize startup time.
	this._startup = DateTime.Now;
    }

    public DateTime GetStartup()
    {
	// We cannot modify the DateTime here.
	return this._startup;
    }
}

Output

(Current time)
Main method

Description. First the Main entry point is defined, and 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 actually assign the readonly field here.

Constructor Tips

Readonly keyword. What the constructor here does is take the current time from the DateTime.Now property and assign it to an unchangeable readonly DateTime field. You are not able to accidentally reassign the startup time.

DateTime Examples DateTime.Now Gets Current Time

Tip: The benefit here is that other code, or the code from your team members, can't change the readonly field, making 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. When you open the following code in IL Disassembler, you will see the compiler has put it in the constructor itself.

IL Disassembler Tutorial
Compiler-generated code [C#]

class Manager
{
    readonly DateTime _startup = DateTime.Now; // <-- Same as first example

    public DateTime GetStartup()
    {
	return this._startup;
    }
}

Constants

Const keyword

In many situations, it is better to use constants instead. For example, if you have a value that was established outside of your program, such as by science or other research, it is better. Also, if your value is constant and you are in complete control of the program, const is better.

Const Example

DLL issues

DLL (Dynamic Link Library)

When you use a const field or declaration, the C# compiler actually embeds the const variable's value directly in the IL code. Therefore, it essentially erases the const as a separate entity. If programs that depend on a const are not recompiled after the const value changes, they may break.

DllImport and Dllexport for DLL Interop

Benchmark

Performance optimization

Here we look at a simple benchmark of readonly and const ints. Also, we include a regular instance of int in the benchmark. In the results, the readonly int and the int field had equivalent performance. The const int was faster by a clear margin. The results were 637 ms, 635 ms, and 317 ms.

Class tested [C#]

class Test
{
    readonly int _value1;  // 1. readonly int
    int _value2 = 1;       // 2. int
    const int _value3 = 1; // 3. constant int

    public Test()
    {
	_value1 = int.Parse("1");
    }

    public int GetValue1()
    {
	return _value1;
    }

    public int GetValue2()
    {
	return _value2;
    }

    public int GetValue3()
    {
	return _value3;
    }
}

Code tested in loops [C#]
    Iterations: 1000000000 (many)

Test test = new Test(); // Outside of loops

if (test.GetValue1() != 1) // 1
{
    throw new Exception();
}

if (test.GetValue2() != 1) // 2
{
    throw new Exception();
}

if (test.GetValue3() != 1) // 3
{
    throw new Exception();
}

Performance results

readonly int: 637 ms
	 int: 635 ms
   const int: 317 ms [fastest]

Error

Warning

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 1 A readonly field cannot be assigned to (except in a constructor or a variable initializer)

ReadOnlyCollection

Programming tip

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. Instead, you can use the ReadOnlyCollection type, which wraps other collections and prevents writes.

ReadOnlyCollection Tips

Summary

The C# programming language

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: readonly and regular fields have equivalent performance, while const is somewhat faster.

Public Static Readonly Field Class Examples
.NET