Search code examples
c#reflectioninheritancesuperclass

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


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.


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.