While just playing with c#, realized a strange thing.
Here is the code:
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Debug.Write(string.Empty);
typeof(string)
.GetField("Empty", BindingFlags.Static | BindingFlags.Public)
.SetValue(null, "Tolgahan");
Console.WriteLine(string.Empty);
// output : Tolgahan
}
}
Why reflection let us to change readonly fields?
The question is “why the setting via reflection is allowed”, not “how to do it”, so it is not a duplicate of Can I change a private readonly field in C# using reflection?.
In the same way the laws of chemistry say that no reaction can cause an atom of one element to change into an atom of another element, but the laws of physics say it happens all the time. Chemistry is a restricted subset of physics in order to simplify problems into a more solvable manner.
Reflection is the physics in this case, where normal programming is the chemistry. It operates in a simpler mindset. Reflection allows you to circumvent that simpler set of rules, exposing you to new processes, but also new dangers.