locked
ASP.NET 3.1 Core : System.FieldAccessException RRS feed

  • Question

  • User-1602535186 posted

    I am getting exception in my Asp.Net core 3.1 application as below

    System.FieldAccessException: Cannot set initonly static field 'Field' after type 'TestReadOnly' is initialized.

    Test.GetType().GetField("ImmediateTest", BindingFlags.NonPublic | BindingFlags.Static)
            .SetValue(Test, Timeout.Infinite);

    Friday, April 3, 2020 7:59 PM

Answers

  • User-474980206 posted

    no, you need to change the "ImmediateTest" field to not be a readonly.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, April 4, 2020 1:20 AM

All replies

  • User-474980206 posted

    the error is pretty clear, you can not set the value of an initonly static field even with reflection. there was a bug in early version of the runtime, where reflection would work.

    public static class MyClass
    {
    	private static readonly string foo;
    	
    	static MyClass()
    	{
    		foo = "hi"; // only way to set - reflection no longer allowed
    	}
    }
    
    

    Friday, April 3, 2020 8:16 PM
  • User-1602535186 posted

    Means SetValues is the problem here. Can You show me How my code will look like after changes ? Do I have to create class and I have to call class to set value.

    Friday, April 3, 2020 8:20 PM
  • User-474980206 posted

    no, you need to change the "ImmediateTest" field to not be a readonly.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, April 4, 2020 1:20 AM