Introduction
Values that cannot be changed at runtime in C# are declared using the readonly and const keywords. However, there are several notable distinctions between these two words.
Constant: What Is It?
Const is a compile-time constant, which means that runtime cannot modify its value; it can only be set at compile time. Declaring global constants, like mathematical constants or other values that aren't anticipated to change while the program is running, is typically done with it. Const values always belong to the class and are not specific to any one instance of the class; they are also inherently static. Additionally, they are accessible from anywhere in the code since they are inherently public.
public class Constants
{
public const string CLIENT_ID = "ClientId";
}
ReadOnly: What Is It?
Conversely, readonly fields are runtime constants, which means that only the class's constructor has the ability to modify them. Their value is predetermined at runtime. Since the readonly fields are instance-level variables, a duplicate of each field exists in each class instance. Additionally, they can be marked as static, indicating that they are part of the class itself rather than a specific class instance. You have to specifically declare the access level because the readonly fields are not inherently public.
public class TestService
{
private readonly ISomeService _someService;
public TestService(ISomeService someService)
{
_someService = someService;
}
}
Key distinctions in C# between readonly and constant
Constants in C# are defined using the readonly and const keywords, although their applications and capabilities differ.
When their values are set is one of the biggest distinctions between readonly and const. Values defined with the const keyword must be set at compile time and will not change at runtime. It implies that const values are decided upon during code compilation rather than execution. Conversely, readonly values are set at runtime and can only have their values assigned within the class constructor.
Const values are also fundamentally different since they are always implicitly static—that is, they are part of the class and not an instance of it. On the other hand, readonly values need to specifically state the access level and can be either instance-level or static.
The following example demonstrates the distinctions between readonly and const:
public class TestClass
{
public const double PI = 3.14;
public readonly string Name;
public TestClass(string name)
{
Name = name;
}
}

Join the conversation! Your thoughts help the community grow.