A question that several new C# developers ask me a lot is the difference between readonly and constant keyword. In this post, I'll explain the difference between these two keywords.
Declaring constant and Readonly fields
In C#, constants can be declared with the const keyword and read-only fields can be declared using the readonly keyword.
class Person
{
public const string Planet = "Earth";
public readonly string Name;
}
Understanding The Difference
Now, let us try to understand the difference between const and readonly.
Difference 1: Constants should be initialized with a value.
The first difference between a constant and a readonly variable is that a constant should be initialized with a value when it is created and readonly fields can be declared without providing a value.
So, the correct way to declare a constant is:
Difference 2: Constants are static by default
The second difference is that the constant fields are static by default. Therefore, we cannot access a constant field of the class in the context of an object.
Difference 3: The value of a readonly member can be changed from the constructor.
Unlike constants, whose value cannot be changed, once created, the value of a readonly member can be assigned from the constructor of a class.
These are the main difference between constants and readonly fields in C#. If I missed any other important points, let me know in the comments below.