Constants

Constants are variables whose values cannot be changed once assigned. In C#, constants are declared using the const keyword. They must be initialized at the time of declaration and remain unchanged throughout the program.

Key Concepts

  • Constants are declared using the const keyword.
  • Their value cannot be changed after initialization.
  • Constants are ideal for values that should not change, like mathematical constants.

Example of Declaring Constants

Code Example

// Declare constants
const double pi = 3.14159;
const int maxStudents = 30;

// Output the constant values to the console
Console.WriteLine($"Value of Pi: {pi}, Max Students: {maxStudents}");

Output:

Value of Pi: 3.14159, Max Students: 30

Code Explanation: The constants pi and maxStudents are declared using the const keyword. These values cannot be changed after initialization, making them ideal for fixed values.

Output Explanation: The values of pi and maxStudents are printed as constants that cannot be modified.