1. const Definition
In C#, const stands for constant. It’s used to declare a field whose value is constant and cannot be modified after it is compiled.
Usage
const fields are declared at the class level and can be accessed directly through the class, not instances of the class.
Characteristics
- Immutable Values: Once assigned, their value cannot be changed.
- Compile-time Constants: The value of a
constfield is determined at compile time. - Static by Nature: Even though not explicitly declared as static,
constbehaves as a static member.
Example
public class Test {
public const double PI = 3.14159;
}
// Accessible as Test.PI
2. readonly Definition
readonly is used to declare a field that can only be assigned at declaration or in a constructor.
Usage
readonly fields are usually instance-specific and can have different values for different instances of the class.
Characteristics
- Value Set at Runtime: Can be assigned during runtime, typically in the constructor.
- Run-time Constants: Suitable for constants that require run-time calculation.
- Instance-level Constant: Each instance of the class can have a different
readonlyvalue.
Example
public class MyClass {
public readonly int MyReadOnlyField;
public MyClass(int value) {
MyReadOnlyField = value;
}
}
3. Comparing const and readonly
Similarities and Differences
While both const and readonly are used for fields that should not change, the key difference lies in when their values are set. const values are set at compile time and are the same for every instance, whereas readonly values are set at runtime and can differ between instances.
When to Use Which
- Use
constfor values that are absolute constants and known at compile time, like mathematical constants. - Use
readonlyfor values that are constant for the object’s lifetime but are different for different instances or require run-time calculation.
4. Reflection and Immutability
One of the intriguing aspects of C# is the ability to inspect and modify program metadata through reflection. Reflection is a powerful tool that allows you to dynamically interact with your code. However, when it comes to immutable fields, particularly const and readonly, reflection behaves differently.
Modifying const Fields: A Misconception
- Immutable at Compile Time:
constfields are literals. Their values are embedded into the IL code at compile time. - No Runtime Existence: Since
constvalues become part of the code that uses them, they don’t exist as fields at runtime. Therefore, they cannot be changed through reflection, as there’s no reference to modify. - Impact of Changes: Changing the source code value of a
constrequires recompiling all assemblies that use it to see the updated value.
Altering readonly Fields with Reflection
- Possible but Risky: Unlike
const,readonlyfields exist at runtime and can technically be modified using reflection. This involves obtaining aFieldInfoobject for the field and usingSetValueto change its value. - Example Code:
var myClassInstance = new MyClass();
var readonlyFieldInfo = typeof(MyClass).GetField("ReadonlyField", BindingFlags.Public | BindingFlags.Instance);
readonlyFieldInfo.SetValue(myClassInstance, 20);
Why You Shouldn’t Do It
- Breaking Encapsulation: Modifying
readonlyfields using reflection breaks the fundamental principle of encapsulation. This practice can lead to code that is hard to debug and maintain. - Potential for Unpredictable Behavior: Such modifications can lead to unpredictable behavior, as the rest of the program does not expect these values to change.
- Compatibility Concerns: This approach might not work consistently across different .NET runtime versions or in different security contexts.
Conclusion
While reflection in C# provides the technical ability to modify readonly fields, it’s generally advised against due to the risks and side effects. It’s important to adhere to the principles of encapsulation and immutability, especially when dealing with const and readonly fields, to maintain the integrity and predictability of your code.
Affiliate promo
If you love learning new stuff and want to support me, consider buying a course from Dometrain using this link: Browse courses – Dometrain. Thank you!
Leave a comment