DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

C# Tip: Use readonly for Immutable Constants

Let’s talk about using readonly for Immutable Constants, a practice that ensures certain values remain unchanged throughout the program’s execution, improving code safety and readability.

Explanation:

By declaring a field as readonly, you ensure it cannot be modified after initialization, except within the class constructor. This is useful for values that need to be set only once and stay constant during program execution. The readonly modifier allows the value to be assigned at the time of object creation or within the constructor, unlike const, which requires immediate initialization with a fixed value and doesn’t allow changes.

This practice is ideal for variables that might depend on construction logic, such as a geometry PI that could depend on runtime precision settings or dynamic configurations.

Code:

public class Circle
{
    public readonly double PI;

    public Circle()
    {
        PI = 3.14159;
    }

    public double CalculateArea(double radius)
    {
        return PI * radius * radius;
    }
}

public class Program
{
    public static void Main()
    {
        Circle circle = new Circle();
        double area = circle.CalculateArea(5);
        Console.WriteLine($"Circle area: {area}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In the example, we have a Circle class with a readonly field named PI, initialized in the constructor. The readonly ensures that the value of PI cannot be changed outside the constructor, ensuring its immutability after the object is created.

Using readonly for Immutable Constants enhances code safety by ensuring that certain values remain unchanged, preventing errors and improving readability. This practice is ideal for variables that rely on construction logic and require immutability.

I hope this tip helps you use readonly to create safe, immutable constants! Until next time.

Source code: GitHub

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay