Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What are the benefits to marking a field as readonly in C#?
The readonly keyword in C# is used to declare a member variable as constant, but allows the value to be calculated at runtime. This differs from a constant declared with the const modifier, which must have its value set at compile time. Using readonly you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.
The readonly modifier provides several benefits including immutability after initialization, runtime value assignment, and thread safety for the field once set.
Syntax
Following is the syntax for declaring a readonly field −
public readonly DataType fieldName;
Following is the syntax for a readonly struct −
public readonly struct StructName {
public readonly DataType fieldName;
}
Benefits of Readonly Fields
| Benefit | Description |
|---|---|
| Runtime Assignment | Values can be calculated and assigned at runtime, unlike const fields |
| Immutability | Once set, the field cannot be modified, ensuring data integrity |
| Thread Safety | Readonly fields are inherently thread-safe after initialization |
| Constructor Flexibility | Can be assigned in any constructor or at declaration |
Using Readonly Fields
When using readonly fields, assignment can only occur during declaration or within the constructor of the same class −
Example
using System;
class Program {
readonly string Name;
readonly DateTime CreatedDate;
public Program() {
Name = "Sample Program";
CreatedDate = DateTime.Now;
}
public Program(string name) {
Name = name;
CreatedDate = DateTime.Now;
}
static void Main(string[] args) {
Program a = new Program();
Program b = new Program("Custom Name");
Console.WriteLine("Program A: " + a.Name + " created at " + a.CreatedDate.ToShortTimeString());
Console.WriteLine("Program B: " + b.Name + " created at " + b.CreatedDate.ToShortTimeString());
}
}
The output of the above code is −
Program A: Sample Program created at 10:30:45 AM Program B: Custom Name created at 10:30:45 AM
Using Readonly Structs
Readonly structs ensure that all fields are immutable, providing better performance and safety −
Example
using System;
public readonly struct Server {
public readonly string Name;
public readonly int Port;
public Server(string name, int port) {
Name = name;
Port = port;
}
public override string ToString() {
return $"Server: {Name} on Port: {Port}";
}
}
class Program {
static void Main(string[] args) {
Server webServer = new Server("Web Server", 80);
Server dbServer = new Server("Database Server", 3306);
Console.WriteLine(webServer);
Console.WriteLine(dbServer);
}
}
The output of the above code is −
Server: Web Server on Port: 80 Server: Database Server on Port: 3306
Readonly vs Const Comparison
| Feature | readonly | const |
|---|---|---|
| Assignment Time | Runtime (constructor or declaration) | Compile time only |
| Value Source | Can use method calls, calculations | Must be literal values |
| Per Instance | Each instance can have different values | Same value for all instances |
| Memory Location | Stored with instance | Inlined at compile time |
Example Comparing readonly and const
using System;
class Configuration {
public const string AppName = "MyApp"; // Compile-time constant
public readonly string Version; // Runtime constant
public readonly DateTime StartTime; // Runtime constant
public Configuration(string version) {
Version = version;
StartTime = DateTime.Now;
}
}
class Program {
static void Main(string[] args) {
Configuration config1 = new Configuration("1.0");
Configuration config2 = new Configuration("2.0");
Console.WriteLine($"App: {Configuration.AppName}");
Console.WriteLine($"Config1: Version {config1.Version}, Started: {config1.StartTime.ToShortTimeString()}");
Console.WriteLine($"Config2: Version {config2.Version}, Started: {config2.StartTime.ToShortTimeString()}");
}
}
The output of the above code is −
App: MyApp Config1: Version 1.0, Started: 10:30:45 AM Config2: Version 2.0, Started: 10:30:45 AM
Conclusion
The readonly keyword in C# provides immutability with flexibility, allowing runtime value assignment while preventing modification after initialization. It offers better performance and thread safety compared to regular fields, and more flexibility than const fields for values that need to be calculated at runtime.
