Will Custode
Will Custode

Reputation: 4594

Read-only Violation Not Handled as Expected

Given the code below, I'm very surprised that an exception is not thrown and would like to know why not. I have a class that has a readonly field that is initialized in the constructor. I then use reflection to get the FieldInfo and call the SetValue method. This results in the otherwise read-only field being writable. My question is why is this allowed to happen?

If this is allowed to happen, that means the readonly keyword is purely for compile-time checking and has very little bearing on the actual instruction generation, I would assume. Thanks in advance for your insights.

public class SomeType
{
    public readonly int RONumber;

    public int LocalMember;

    public SomeType()
    {
        RONumber = 32;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var st = new SomeType
        {
            LocalMember = 8
        };

        var ron1 = st.RONumber;

        var type = typeof(SomeType);

        var ronField = type.GetField("RONumber");

        ronField.SetValue(st, 405);

        var ron2 = st.RONumber; // ron2 is 405!
    }
}

Upvotes: 4

Views: 95

Answers (1)

KirkSpaziani
KirkSpaziani

Reputation: 1972

A readonly field tells the compiler to prevent you from writing code that will mutate that value. If you use reflection you can bypass those checks and do basically whatever you want.

Note that is different from a const field, which is a compile time constant.

Upvotes: 1

Related Questions