Set value of private field
Try this (inspired by Find a private field with Reflection?):
var prop = s.GetType().GetField("id", System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance);
prop.SetValue(s, "new value");
My changes were to use the GetField
method - you are accessing a field and not a property, and to or NonPublic
with Instance
.
Evidently, adding BindingFlags.Instance
seems to have solved it:
> class SomeClass
{
object id;
public object Id
{
get
{
return id;
}
}
}
> var t = typeof(SomeClass)
;
> t
[Submission#1+SomeClass]
> t.GetField("id")
null
> t.GetField("id", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
> t.GetField("id", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
[System.Object id]
>