Constants

Constants

 Constants represent information that is hard-coded into the application.
  • Defined in a class
A constant is defined in a class and hold a hard-coded value that is expected to never change.

 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
So a constant can't be assigned to a value returned from a method or retrieved from a file, nor can it be an object instance.
  • Compiled into every location that references it
  • Are static
Constants are by definition 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

Popular posts from this blog

Constant vs Read-Only

FAQ: