Tishy

C# const / readonly / static

Sep 27th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. /* It's good behaviour to declare variables as readonly/const if they are not supposed to change (mutable).
  2. - Const is used for variables that get initialized at compile-time, basically while the program loads
  3. - Readonly is used for variables that get initialized at run-time, well... while the program runs already
  4. - Any variable declared as const will also, implicitly, be declared static
  5. - Static methods/variables don't need an object to be called
  6. - non-static methods can only be called on objects, that's why my method is static in this example
  7. Quite sure there are exceptions, but round-about every initialization that calls a method can't be const -> happens at run-time
  8. Lots of programing language have all variables const by default and need a keyword for it to be mutable/changeable
  9. */
  10.  
  11. //this works:
  12.         readonly int bla = AddFive(4); //used with myObject.bla
  13.  
  14.         static int AddFive(int number) //used with MyClass.AddFive()
  15.         {
  16.             const int numberFive = 5;
  17.             number += numberFive;
  18.             return number;
  19.         }
  20.  
  21. //this works:
  22.         static readonly int bla = AddFive(4); //used with MyClass.bla
  23.  
  24.          static int AddFive(int number) //used with MyClass.AddFive()
  25.         {
  26.             int numberFive = 5;
  27.             number += numberFive;
  28.             return number;
  29.         }
  30.  
  31. //this doesn't:
  32.         const int bla = AddFive(4); //error: cannot be marked static
  33.  
  34.         static int AddFive(int number)
  35.         {
  36.             const int numberFive = 5;
  37.             number += numberFive;
  38.             return number;
  39.         }
  40.  
  41. //this works:
  42.         const int bla = 9;
  43. //this also works:
  44.         const int yada = 4 + 5;
Add Comment
Please, Sign In to add comment