Understanding the Difference Between const and readonly in Csharp

Understanding the Difference Between const and readonly in Csharp

šŸš€ 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! 😊
Sampada Lohite

Sampada Lohite

January 5, 2025 at 1:59 PM

Hello Mayur, I have sent you a connection request. I would like to apply for Angular Team Lead. Thanks

Alex Parker

Alex Parker

January 7, 2025 at 8:10 AM

I would like to apply for āž Python UI Automation Engineer. Sent you invite. Thanks

New User

Priya Singh

January 8, 2025 at 10:00 AM

Thank you for this opportunity. I’m interested in the React Developer position.

Leave a Reply

Your email address will not be published. Required fields are marked *