fork download
  1. using System;
  2. using System.Reflection;
  3.  
  4. public class Test
  5. {
  6. public static void Main()
  7. {
  8. var yoba = new Yoba();
  9. Console.WriteLine(yoba.Size);
  10.  
  11. // error CS0200: Property or indexer `Yoba.Size' cannot be assigned to (it is read-only)
  12. // yoba.Size = 5;
  13.  
  14. var field = typeof (Yoba).GetField("<Size>k__BackingField",
  15. BindingFlags.Instance | BindingFlags.NonPublic);
  16.  
  17. field.SetValue(yoba, 5);
  18. Console.WriteLine(yoba.Size);
  19. }
  20. }
  21.  
  22. public class Yoba
  23. {
  24. public int Size { get; } = 2;
  25. }
  26.  
  27. public class OldYoba
  28. {
  29. private readonly int _size = 2;
  30.  
  31. public int Size
  32. {
  33. get { return _size; }
  34. }
  35. }
Success #stdin #stdout 0.04s 23944KB
stdin
Standard input is empty
stdout
2
5