Constants

  • Constants are static by default.
  • They must have a value at compilation-time (you can have e.g. 3.14 * 2 + 5, but cannot call methods).
  • Could be declared within functions.
  • These are copied into every assembly that uses them (every assembly gets a local copy of values).
  1. using System;
  2. namespace ConstantExample
  3. {
  4. class ConstantExample
  5. {
  6. private const int PI = 3.14;
  7. public static void Main()
  8. {
  9. //You have to initialize Const variables while declaration
  10. const int RollNo = 1284;
  11. //Valid scenario
  12. const int Age = 10 + 13;
  13. const string Name = "Satish Kumar";
  14. // Reassigning a const variable is not allowed.
  15. RollNo = 1405; // Will result compile time error.
  16. Age++; // Will result compile time error.
  17. Console.WriteLine(Name);
  18. Console.Read();
  19. }
  20. }
  21. }
Readonly
  • Must have set value, by the time constructor exits.
  • Are evaluated when instance is created.
  • You can use static modifier for readonly fields.
  • readonly modifier can be used with reference types.
  • readonly modifier can be used only for instance or static fields, you cannot use readonly keyword for variables in the methods.
  1. using System;
  2. namespace ReadOnlyExample
  3. {
  4. class ReadOnlyTest
  5. {
  6. //You have to initilize readonly varabiles while declaration or in constructor
  7. readonly int RollNo = 1284;
  8. //Valid scenario
  9. readonly int Age;
  10. readonly string Name = "Satish Kumar";
  11. //readonly fields can be initlized in constructor
  12. public ReadOnlyTest (string name)
  13. {
  14. Age = 23;
  15. Name = name;
  16. }
  17. public changeName(string newName)
  18. {
  19. Name = "Satish Kumar Vadlavalli"; ; // Will result error.
  20. }
  21. }
  22. class ReadOnlyExample
  23. {
  24. public static void Main()
  25. {
  26. ReadOnlyTest obj = new ReadOnlyTest("Satish");
  27. Console.Read();
  28. }
  29. }
  30. }
Difference between const and readonly

  • const fields has to be initialized while declaration only, while readonly fields can be initialized at declaration or in the constructor.
  • const variables can declared in methods ,while readonly fields cannot be declared in methods.
  • const fields cannot be used with static modifier, while readonly fields can be used with static modifier.
  • A const field is a compile-time constant, the readonly field can be used for run time constants.
A blog without comments is not a blog at all, but do try to stay on topic. Please comment if you have any questions or leave your valuable feedback. Happy Learning.