Understanding the 'const' Keyword in C#

C# const Keyword

In C#, the const keyword is used to declare a constant variable. A constant is a value that cannot be modified once it is assigned and must be initialized with a value at the time of declaration. Constants are useful for defining fixed values that remain the same throughout the program's execution.Here's how you declare a constant using the const keyword:

public class ExampleClass
{
    // Constant declaration.
    public const int MyConstantValue = 10;

    // Other members and methods of the class go here.
}

In this example, MyConstantValue is a constant of type int with a value of 10. Once assigned, the value of MyConstantValue cannot be changed later in the program.

Key points to note about const:

  1. The const keyword can only be used with primitive data types (e.g., int, float, double, char, etc.) and strings.

  2. Constant variables must be initialized with a constant expression at the time of declaration. This means you cannot assign the value of a variable or an expression that involves runtime calculations.

  3. Constants are implicitly static, meaning they belong to the type itself rather than instances of the type. Therefore, you can access a constant using the class name without creating an instance of the class.

Here's an example of how you can use a constant in C#:

public class MathOperations
{
    public const double Pi = 3.14159;

    public double CalculateCircleArea(double radius)
    {
        return Pi * radius * radius;
    }
}

// Usage example:
double circleArea = MathOperations.Pi * 5.0 * 5.0;

In this example, we declare a constant Pi in the MathOperations class to store the value of π (pi). The CalculateCircleArea method then uses this constant to calculate the area of a circle.

Constants provide a way to use meaningful names for fixed values in your code and help improve code readability and maintainability. Additionally, using constants allows the compiler to optimize your code by replacing references to the constant with its actual value during compilation.