Skip to content

Instantly share code, notes, and snippets.

@ValdemarOrn
Created July 4, 2013 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ValdemarOrn/5927071 to your computer and use it in GitHub Desktop.
Save ValdemarOrn/5927071 to your computer and use it in GitHub Desktop.

Just how read-only is "readonly" in C#?

Did you know you can modify read-only fields via reflection?

class Program
{
public readonly int Val;
public Program()
{
Val = 42;
}
static void Main(string[] args)
{
var p = new Program();
var now = p.Val;
// This is a compile-time error
p.Val = 45; // try commenting out this line, see what happens...
// But this works just fine
p.GetType().GetField("Val").SetValue(p, 43);
var after = p.Val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment