1

I want to change the value of a static readonly field, the codes executes without any exception, but a very strange thing is:looks it is effected when use reflection, but not really working.

    private class TestReadOnly
    {
        public static readonly int Field;
    }
    [TestMethod]
    public void TestReadOnlyField()
    {
        FieldInfo field = typeof(TestReadOnly).GetField(nameof(TestReadOnly.Field));

        Console.WriteLine(field.GetValue(null));

        field.SetValue(null, 0xFF);

        Console.WriteLine(field.GetValue(null));

        Console.WriteLine(TestReadOnly.Field);
    }

output:

0
255
0

my question is:is there any solution to make theme same?

dexiang
  • 1,345
  • 16
  • 23
  • Strange. WIth an instance readonly field, we get 0 / 255 / 255... The hidden question is why we can change the value using reflexion... It should throw an exception, isn't it? –  Oct 09 '19 at 04:15
  • It's a duplicate of https://stackoverflow.com/a/8747554/2956272, but the answer doesn't work anymore. The natural guess is that `Field` was optimized into the actual constant in the generated code. If that's the case, you can't change it (and it's a good thing, I think). –  Oct 09 '19 at 04:20
  • @dyukha It is optimised, but during runtime (by the JIT), not during compilation (you won't see anything obvious in the IL). This is probably closer to a duplicate to [this thread](https://stackoverflow.com/q/54380905/5623232) – NPras Oct 09 '19 at 07:56

0 Answers0