DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited 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

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more →

Top comments (0)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay