Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 358
Custodio Avatar asked Sep 09 '09 19:09

Custodio


1 Answers

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.

like image 123
JaredPar Avatar answered Sep 24 '22 21:09

JaredPar