DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Tip: Use const for Truly Constant Values

Let’s talk about using const for Truly Constant Values, a practice that ensures fixed values remain immutable at compile time, making the code more efficient.

Explanation:

Declaring a variable as const means it’s a compile-time constant, meaning its value is fixed and cannot be changed at runtime. const is ideal for values that never change, like mathematical numbers or default values that don’t depend on any logic. Unlike readonly, const is more restrictive since its value must be assigned immediately and cannot depend on dynamic variables or the constructor.

This practice helps improve performance, as the compiler treats const as a direct substitution of the value, optimizing resource usage.

Code:

public class Math
{
    public const double PI = 3.14159;

    public double CalculateCircumference(double radius)
    {
        return 2 * PI * radius;
    }
}

public class Program
{
    public static void Main()
    {
        Math math = new Math();
        double circumference = math.CalculateCircumference(5);
        Console.WriteLine($"Circumference: {circumference}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In the example, we have a Math class that defines the constant PI with const. Since PI is a fixed, universal value, const ensures it remains immutable and optimized at compile time, enhancing performance.

Using const for Truly Constant Values ensures that fixed values remain immutable and optimized at compile time, resulting in more efficient and secure code. This practice is ideal for universal values that never change.

I hope this tip helps you use const to optimize and protect constant values in your code! Until next time.

Source code: GitHub

Top comments (0)