Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the value of a static readonly field using reflection in c#?

The SetFields method in the fieldInfo class takes objects as the first parameter. Is there a way to change the value of the static readonly fields using reflection in C#?

So far I have

var field = typeof(ClassName).GetField("FieldName",BindingFlags.Instance|BindingFlags.NonPublic);
like image 404
unj2 Avatar asked Jan 05 '12 18:01

unj2


2 Answers

If you want to get a static field then you should be using BindingFlags.Static instead of BindingFlags.Instance, as the latter is for instance fields.

You can then use field.SetValue(null, newValue) to set the value. Note that null may be passed as the target parameter, because no object instance is needed. Assuming you have sufficient privileges, reflection will happily change the value of a readonly field.

like image 160
Greg Beech Avatar answered Nov 11 '22 18:11

Greg Beech


You're close. Your BindingFlag is incorrect. Instance means instance field Instead, you should use BindingFlags.Static:

var field = typeof(ClassName).GetField("FieldName",BindingFlags.Static|BindingFlags.NonPublic);
like image 27
vcsjones Avatar answered Nov 11 '22 17:11

vcsjones