[C#] C# Named Constants

Date:     Updated:

Categories:

Tags:

📋 This is my note-taking from what I learned in the class “Programming 1 - COMP 100-002”


What are Named Constants?

  • Are immutable.
    Values that would not change in the life of the program.
  • Must be known at compile time (must be set at declaration).
    Has to be a literal or a constant expression.
  • Only C# built-in types may be declared constant (except objects).


Usage

  • Value is set at declaration.

  • In your code, it is used like a normal variable.

  • It can not appear on the left side of an expression after declaration.
    → You may not assign a new value to it.

Example:

const string COMPANY_NAME = "Centennial College";
const char SPACE = ' ';
const double TAX_RATE = 0.13;
const int LEGAL_AGE = 18;
const int MONTHS = 12, DAYS = 365;
const double DAYS_PER_MONTH = DAYS / (double)MONTHS;

cost = price * (1 + TAX_RATE);


Why Use Named Constants?

  • Improves readability of your code.
    You see words not values.
  • Code maintenance.
    Easier to edit code.
    If you have the same literal value for two items and you want to change one of them, it is almost impossible to make a certain change.
  • Security.
    Value may not change during execution of program.


“ToUpper” and “ToLower” Methods

  • These string methods returns a string that is all uppercased or all lowercased.
  • They only work with strings (Does not work with char).
  • It is convenient when doing string comparisons.
  • If a user is asked to the two letter province code.
  • For this province the user response might be any of the following:
    → ON, On, on, oN
  • To simplify processing the response, you can decide to compare either the uppercased or the lowercased version the response.

Example:

Console.Write("What shape would you like to work with? ");

string shape = Console.ReadLine();

switch(shape.ToLower())
{
  case "square":
    Console.WriteLine($"The area of a {shape} is length x width");
    break;
  case "triangle":
    Console.WriteLine($"The area of a {shape} is base x height / 2");
    break;
}

Console.WriteLine($"{shape} -> {shape.ToUpper()}"); // shape does not change
  • Named constants is having a name for a value that may not change.
  • You have the confidence that it will not change in the execution of the application.
  • Your code is more readable.
    • You see a descriptive name instead of a literal value.
  • Code maintenance is simpler.




Back to Top

See other articles in Category CS

Leave a comment