CHASH Tutorial



C# CONSTANTS


C# Constants

A constant is a variable whose value cannot be changed once it is assigned. Constants are useful for values that must remain the same throughout the program.

Declaring Constants

To declare a constant in C#, use the const keyword followed by the type and name:

const int DaysInWeek = 7;
const double Pi = 3.14159;
  

Key Characteristics

  • The value must be assigned when declared.
  • Constants cannot be changed after declaration.
  • Constants are implicitly static (shared across all instances).
  • Only primitive or compile-time constant values can be assigned.

Example: Using Constants

using System;

class Program
{
    const int MaxScore = 100;

    static void Main()
    {
        Console.WriteLine("The maximum score possible is: " + MaxScore);

        // MaxScore = 90; // ❌ Error! Cannot change a constant value.
    }
}
  

Why Use Constants?

- Improve code readability by giving meaningful names to fixed values.
- Avoid accidental changes to values that should remain the same.
- Make maintenance easier by changing the value in one place only.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review