Understanding the Difference Between const and readonly in Csharp

Explore the key differences between const and readonly in C#. Learn when and how to use each for optimal code performance and maintainability.

🚀 C#/.NET Tip - Const vs Readonly 💡

💎 Understanding the Difference Between const and readonly in C#

🔹 Const:
Constants are static by default.
They must be assigned a value at compile-time.
Can be declared within functions.
Each assembly using them gets its own copy of the value.
Can be used in attributes.

🔹 Readonly:
Must be assigned a value by the time the constructor exits.
Evaluated when the instance is created.
Static readonly fields are evaluated when the class is first referenced.

Example:

public class MathConstants
{
    public const double Pi = 3.14159;
    public readonly double GoldenRatio;
    public MathConstants()
    {
        GoldenRatio = (1 + Math.Sqrt(5)) / 2;
    }
}

Explanation:

  • Pi is a const and its value is fixed at compile-time. It cannot be changed and is the same across all instances.
  • 2. GoldenRatio is a readonly field, which is calculated at runtime when an instance of MathConstants is created. This allows for more flexibility as the value can be set in the constructor.

This example highlights how const is used for values that are truly constant and known at compile-time, while readonly is used for values that are determined at runtime but should not change after being set.

I hope this helps! 😊


Notice Inappropriate?

If you come across any inappropriate content, please report it to our administrators!

Leave a Reply

Please login to post comments.

Top