Constants
Constants
Constants represent information that is hard-coded into the application.
- Defined in a class
Example:
public const double pi = 3.14;
public const int Red = 0xFF0000;
public const double InchesPermeter = 39.37;
- Must be assigned to an expression that can be fully evaluated at compile time, think of constant as a "compile-time" constant value
- Compiled into every location that references it
- Are static
That means we don't have to create an instance of the class to access them.
We instead access them using the class name.
Declaring A Constant
Declaring a constant is a bit different from declaring a backing field.
- Optional accessibility modifier (but is often publicly accessible to the application).
- Constant needs no property to protect it. (because it's valued never change)
- Const keyword, A constant must include the const keyword, which defines it as a constant.
- Data type, constants can only be numbers, boolean value, or strings.
- Name, PascslCasing
- Assigned value, a constant must be initialized to value.
Constant Best Practices
Do:
- Class Naming, define a meaningful name use PascalCasing
- use for the compile-time value that will never change
Avoid:
- class naming, single character name, Abbreviations, All upper case
- For fields that could change time.
Comments
Post a Comment