0

I'm trying to change the value of a public static readonly string inside System.Web.Mvc.

Specifically, I'm trying to achieve what the marked answer on this post suggests, and I'm using the following code:

var htmlHelper = typeof(HtmlHelper);
var field = htmlHelper.GetField("ValidationInputCssClassName", BindingFlags.Public | BindingFlags.Static);
if (field != null)
{
    // existing value is "input-validation-error"
    field.SetValue(null, "has-error");
}

However, after I set the value, GetValue indicates that nothing has changed, and this is borne out on the resultant webpage.

The only explanation I can think of for this is that .NET's JIT compiler is caching the readonly fields before I can change them.

Or does anyone have any better suggestions?

UPDATE: If I call field.GetValue(null) immediately after the call to SetValue I get the value 'has-error', exactly as I'd expect to, which suggests that the static readonly value can be changed. However, when the webpage loads I find the presence of the unchanged field.

UPDATE 2: I believe the above code is modifying the public static readonly string fields. My earlier confusion was due to (1) checking GetValue in the wrong event (or possibly not for all threads), and (2) the webpage still using the old value because, as I've only just now realised, is due to Microsoft's jquery.validate.unobtrusive.js script having the name of the CSS class hard-coded. And that's why I kept on seeing the old value on the page, not because Reflection wasn't updating the field values. Apologies for any time wasted.

Community
  • 1
  • 1
awj
  • 7,482
  • 10
  • 66
  • 120
  • Why do you expect a _readonly_ value to change? – marekful Nov 06 '13 at 14:47
  • I thought that was something that Reflection offered, no? – awj Nov 06 '13 at 14:48
  • I'd strongly recommend *against* doing this, and rather coming up with a different way to solve your problem. But it is possible. See http://stackoverflow.com/q/934930/1127114, for example. If you can't make that work and you really want to shoot yourself in the head this way, then post a small but complete example that doesn't work, and perhaps we can help you out. – Jim Mischel Nov 06 '13 at 15:42

1 Answers1

0

A readonly value can't be changed after initialization (inline or in the constructor).

Yosi Dahari
  • 6,794
  • 5
  • 24
  • 44