Did you know you can modify read-only fields via reflection?
Created
July 4, 2013 11:55
-
-
Save ValdemarOrn/5927071 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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