Const vs. Readonly vs. Static In C#
3 min read · — #csharp-interview#junior
C# introduces key terms such as const
, readonly
, and static
readonly
that could seem bewildering at first. However,
slight nuances distinguish these keywords, leading to different execution paths in your applications. This post is your
comprehensive guide to understand and effectively employ these keywords in your software development process.
Understanding Const
The const
keyword in C# is utilized to declare a constant. What makes these variables unique is that they must hold a
value at compile time and are implicitly static
. This means a single instance of the variable is generated and shared
amongst all objects. When using const
in a class, it can be accessed via the class's name. In more intricate
applications where a solution is referenced across assemblies, a local copy of the constant is fetched.
Below is an example of a const
variable:
const string myConstant;
However, this will cause a compile-time error as constants are required to be initialized with a value at the time of declaration. The correct form would look like this:
const string myConstant = "Constants are cool!"
In a function, a const
can be defined like this:
static string TestConst()
{
const string solved = "This is a viable solution!";
return solved;
}
To call this function:
Console.WriteLine($"The constant returned was: {TestConst()}");
This code returns the following console output:
The constant returned was: This is a viable solution!
Exploring Readonly
The readonly
keyword shares many similarities with const
, but with a few distinctions. readonly
can be applied to
fields (not local variables) and can be initialized either at declaration or within the constructor of a class. It
guarantees that a variable instance or property of an object can't be altered after initialization.
Here's how to use readonly
in your code:
public readonly string compileTime = "This is initialized at compile time";
public readonly string runTime;
An example of a readonly
variable initialized at runtime is shown below:
class Student
{
public readonly string FullName;
public Student(string name)
{ FullName = name; }
}
You can instantiate the class and print the FullName as follows:
Student student = new Student("Roman Fairushyn");
Console.WriteLine($"The full name of the student is : {student.FullName}");
This will output:
The full name of the student is : Roman Fairushyn
Core Difference
To differentiate, readonly
and const
values are known at different stages of the application's lifecycle. For readonly
,
the latest value is determined at runtime, whereas for const
, it must be known at compile time. Both keywords deal with
immutable data types, indicating their values can't be changed during the application's lifetime.
Under the hood, a const
variable's value is embedded into the Intermediate Language (IL) code post initialization,
meaning no memory allocation for constants is done at runtime. However, a readonly
variable is not a constant; it's
stored in the loader heap, which is a memory type that can't be allocated until the type is loaded. Therefore, readonly
values are accessible only at runtime.
A crucial distinction is their binary versioning behavior. For const
, the value is embedded at compile-time, and changes
in a different assembly require recompilation. However, for readonly
, the value is fetched at runtime, and changes are
immediately reflected without recompiling the assembly.
Conclusion
Both const
and readonly
keywords aim to maintain the immutability of a variable's value during the application's
execution. Their main difference lies in their initialization timing (const
at compile-time, readonly
at runtime) and
their scope (const
is class-level, readonly
is instance-level). Another important distinction is accessing a const
variable as "ClassName.VariableName" vs. accessing a readonly
variable as "InstanceName.VariableName". This guide aimed
to introduce these differences and similarities to support your understanding and application of these keywords in C#
programming.