Can I change a private readonly inherited field in C# using reflection?

c#, inheritance, reflection, superclass

Solution

Yes, it is possible to use reflection to set the value of a readonly field after the constructor has run

var fi = this.GetType()
             .BaseType
             .GetField("_someField", BindingFlags.Instance | BindingFlags.NonPublic);

fi.SetValue(this, 1);

EDIT

Updated to look in the direct parent type. This solution will likely have issues if the types are generic.

Problem

like in java I have: ``` Class.getSuperClass().getDeclaredFields() ``` how I can know and set private field from a superclass? I know this is strongly not recommended, but I am testing my application and I need simulate a wrong situation where the id is correct and the name not. But this Id is private.

Original source