code_junkie

What is the difference between const and readonly?

Nov 10th, 2011
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. public class Const_V_Readonly
  2. {
  3. public const int I_CONST_VALUE = 2;
  4. public readonly int I_RO_VALUE;
  5. public Const_V_Readonly()
  6. {
  7. I_RO_VALUE = 3;
  8. }
  9. }
  10.  
  11. public const int CM_IN_A_METER = 100;
  12.  
  13. public readonly float PI = 3.14;
  14.  
  15. public class Const_V_Readonly
  16. {
  17. public const int I_CONST_VALUE = 2;
  18. public readonly char[] I_RO_VALUE = new Char[]{'a', 'b', 'c'};
  19.  
  20. public UpdateReadonly()
  21. {
  22. I_RO_VALUE[0] = 'V'; //perfectly legal and will update the value
  23. I_RO_VALUE = new char[]{'V'}; //will cause compiler error
  24. }
  25. }
  26.  
  27. public class Sample {
  28. private readonly string ro;
  29.  
  30. public Sample() {
  31. ro = "set";
  32. }
  33.  
  34. public Sample(string value) : this() {
  35. ro = value; // this works even though it was set in the no-arg ctor
  36. }
  37. }
  38.  
  39. var fi = this.GetType().BaseType.GetField("_someField", BindingFlags.Instance | BindingFlags.NonPublic);
  40. fi.SetValue(this, 1);
  41.  
  42. public static class Text {
  43. public const string ConstDescription = "This can be used.";
  44. public readonly static string ReadonlyDescription = "Cannot be used.";
  45. }
  46.  
  47. public class Foo
  48. {
  49. [Description(Text.ConstDescription)]
  50. public int BarThatBuilds {
  51. { get; set; }
  52. }
  53.  
  54. [Description(Text.ReadOnlyDescription)]
  55. public int BarThatDoesNotBuild {
  56. { get; set; }
  57. }
  58. }
Add Comment
Please, Sign In to add comment