Today’s tip is all about the readonly modifier.
A value or a reference type object can be declared using the readonly modifier keyword, what makes possible a value to be assigned on either declaring the object or within a constructor.
What about the constants?
The two differences between constants and readonly modifiers are:
1. Constants must be initialized only during the declaration;
2. Only literal values must be used to initialize a constant object while readonly objects may be initialized with either literal values or references to other objects.
The syntax is pretty straightforward:
// Declare the object and initialize with a literal value
readonly int b = 100;
// Declare the object and initialize with other object
readonly int b = a;
// Declare the object and initialize it on constructor
readonly int b;
/// Class constructor
/// <param name=”b”>Parameter</param>
public MyConstructor(int b)
a = b;