Monday, April 24, 2023

What is the difference between const and readonly in C# ?

In C#, both 'const' and 'readonly' keywords are used to declare constant values, but they have some differences.
  1. Initialization: 
    • 'const' fields must be initialized at the time of declaration with a constant value.
    • 'readonly' fields can be initialized either at the time of declaration or in a constructor. 
  2. Mutability: 
    • 'const' fields are implicitly 'static' and 'readonly', meaning they cannot be changed after initialization.
    • 'readonly' fields can be mutable or immutable, depending on their type. 
  3. Scope: -
    • 'const' values are compile-time constants, meaning they are evaluated and replaced at compile-time. Therefore, they can only be used in the same assembly or code file where they are defined. 
    • 'readonly' values are evaluated at runtime, and therefore can be used in different assemblies or code files.
Here's an example to demonstrate the differences:
public class MyClass
{
    public const int MyConstValue = 10;
    public readonly int MyReadonlyValue;

    public MyClass(int value)
    {
        MyReadonlyValue = value;
    }
}
In the above example, 'MyConstValue' is a 'const' field that is initialized with a constant value of 10 at the time of declaration. It cannot be changed later.
 
'MyReadonlyValue' is a 'readonly' field that is initialized in the constructor. It can be changed in the constructor but cannot be changed outside of it.
 
To summarize, use 'const' when you have a value that will never change, and use 'readonly' when you have a value that might change, but you want to restrict its modification after initialization.

No comments:

Post a Comment