C#
const
readonly
programming
.NET

What is the difference between const and readonly in C?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In C#, both const and readonly are used to define fields or variables whose values cannot be changed. However, they function in distinct ways and are suited to different scenarios. Understanding the difference between const and readonly is essential for optimal usage, particularly in scenarios involving memory management and program efficiency.

Technical Explanation

const

  • Definition: The const keyword is used for defining compile-time constants. This means that the value must be specified at the time of declaration and cannot be altered thereafter.
  • Initialization: A const must be initialized with a value at the time of its declaration. This value can only be a compile-time constant.
  • Scope: const fields are implicitly static. Thus, they are shared across all instances of a class and can be accessed using the class name.
  • Data types supported: Only primitive data types (such as int, string, double, and char) and enums can be declared as const.
  • Performance: Because const values are substituted at compile time, they can make programs run faster as they remove the need for a runtime lookup.

Example

csharp
1// Example of const
2public class Circle
3{
4    public const double Pi = 3.14159;
5    public double GetArea(double radius)
6    {
7        return Pi * radius * radius;
8    }
9}

readonly

  • Definition: The readonly keyword is used to define runtime constants. These can be initialized either at declaration or in a constructor.
  • Initialization: Unlike const, readonly fields can be initialized multiple times depending on the context, allowing different values depending on instantiation or scenarios.
  • Scope: Unlike const, readonly fields can be instance-level, meaning each instance of a class can have its own copy.
  • Data types supported: readonly is more versatile, allowing any data type, including complex types like object instances, arrays, and lists.
  • Usage scenarios: Use readonly for variables whose values depend on runtime information, such as current date and time, configuration data, or environment settings.

Example

csharp
1// Example of readonly
2public class Configuration
3{
4    public readonly DateTime InitializationTime;
5
6    public Configuration()
7    {
8        InitializationTime = DateTime.Now;
9    }
10}

Key Differences between const and readonly

Featureconstreadonly
Initialization TimeCompile-timeRuntime
Initialization LocationAt declarationDeclaration or constructor
Modifiable TypesPrimitives and enumsAny data type
Static vs InstanceImplicitly staticCan be instance or static
Value SubstitutionSubstituted at compile timeEvaluated at runtime
Use case scenariosFixed values across buildsValues dependent on runtime conditions

Additional Details

Usage Considerations

  • Thread Safety: Both const and readonly fields are inherently thread-safe as their values cannot change once set. However, if a readonly field contains a reference to a mutable object, the object's data can be changed.
  • Versioning: As const values are embedded into the assembly at compile time, if the value of a const changes, recompilation of dependent assemblies is necessary.
  • Memory Efficiency: Using const can be more memory efficient for primitive types since the value is embedded directly, eliminating the need for an object reference.

Understanding these differences ensures that developers properly use const and readonly to their advantage, improving code readability, efficiency, and maintenance. By recognizing the appropriate contexts for each, one can write robust and optimized C# applications.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.