const vs readonly in dotnet
In C#, both `const` and `readonly` are used to declare constants, but they have different use cases and characteristics.
1. const:
- Constants declared with the `const` keyword are implicitly static members. They must be initialized with a constant value during declaration and cannot be modified afterwards.
- `const` values are implicitly `static`, meaning they belong to the type itself rather than to a specific instance of the type.
- They are evaluated at compile-time and are replaced with their actual values in the compiled code.
- `const` members can be used in expressions that require constant values, such as array sizes or case labels in switch statements.
Example:
csharp
public class ConstantsClass
{
public const int MaxValue = 100;
// ...
}
2. readonly:
- `readonly` fields are instance members that are initialized either at the time of declaration or in a constructor. They can be modified only within the constructor of the class where they are declared.
- `readonly` fields can have different values for different instances of the same class, unlike `const` members which are shared across all instances of the class.
- They are evaluated at runtime and can have different values for different instances of the class.
- `readonly` members are useful when you want to assign a constant value to an instance member that might vary from one instance to another.
Example:
csharp
public class ReadOnlyExample
{
public readonly int InstanceValue;
public ReadOnlyExample(int value)
{
InstanceValue = value; // Initialized in the constructor
}
}
Key Differences:
- `const` members are implicitly `static` and are shared across all instances of the class. `readonly` members are instance-specific and can have different values for different instances.
- `const` values are evaluated at compile-time, while `readonly` values are evaluated at runtime.
- `const` members must be initialized at the time of declaration, while `readonly` members can be initialized in the constructor.
In summary, use `const` when you want a constant value that is the same for all instances of a class, and use `readonly` when you want a constant value that can vary from one instance to another but doesn't change once it's set in the constructor. Choose the appropriate keyword based on the scope and mutability requirements of your constants.
No comments:
Post a Comment
Comments Welcome