Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* It's good behaviour to declare variables as readonly/const if they are not supposed to change (mutable).
- - Const is used for variables that get initialized at compile-time, basically while the program loads
- - Readonly is used for variables that get initialized at run-time, well... while the program runs already
- - Any variable declared as const will also, implicitly, be declared static
- - Static methods/variables don't need an object to be called
- - non-static methods can only be called on objects, that's why my method is static in this example
- Quite sure there are exceptions, but round-about every initialization that calls a method can't be const -> happens at run-time
- Lots of programing language have all variables const by default and need a keyword for it to be mutable/changeable
- */
- //this works:
- readonly int bla = AddFive(4); //used with myObject.bla
- static int AddFive(int number) //used with MyClass.AddFive()
- {
- const int numberFive = 5;
- number += numberFive;
- return number;
- }
- //this works:
- static readonly int bla = AddFive(4); //used with MyClass.bla
- static int AddFive(int number) //used with MyClass.AddFive()
- {
- int numberFive = 5;
- number += numberFive;
- return number;
- }
- //this doesn't:
- const int bla = AddFive(4); //error: cannot be marked static
- static int AddFive(int number)
- {
- const int numberFive = 5;
- number += numberFive;
- return number;
- }
- //this works:
- const int bla = 9;
- //this also works:
- const int yada = 4 + 5;
Add Comment
Please, Sign In to add comment