A Complete Guide - Const and Read Only Keywords in C#
Const and Readonly Keywords in C#: Explanation and Important Information
Const Keyword
Definition:
The const keyword is used to declare a constant field or local variable. Constants are compile-time entities and their values are embedded directly into the intermediate language (IL) code by the compiler.
Key Characteristics:
- Compile-Time Evaluation: The value of a
constfield must be known at compile time. This means you can only assign literals, otherconstvariables, or the result of a simple arithmetic operation involving them. - Immutability: Once assigned, the value of a
constfield cannot be changed. - Implicit Static: When declaring a
constfield outside of a constructor or method (i.e., at the class level), it implicitly becomes static. Thus, constants can be accessed without instantiating the class. - Type Inference: A
constfield can be initialized without explicitly specifying its type if the compiler can infer it from the right-hand side of the assignment. - Literal Types: Only certain types can be declared as
const, including primitive data types (int, float, string, etc.), enums, and structs where all fields are themselvesconst.
Usage Example:
public class MathConstants
{
public const double Pi = 3.14159;
public const int MaxStudents = 30;
// Error: Not allowed because it's not a compile-time constant
// public const DateTime TodayDate = DateTime.Now;
}
Important Points:
- Since
constvalues are embedded into the IL code, any changes made to the originalconstvalue require recompiling all dependent assemblies. - They are useful when the value will never change and needs to be available during compilation.
- Being static, they are shared across all instances of the class.
Readonly Keyword
Definition:
The readonly keyword is used to modify a field that can only be assigned during declaration or within a constructor of the same class. After initialization, a readonly field can no longer be modified, providing runtime immutability.
Key Characteristics:
- Runtime Evaluation: Unlike
const,readonlyfields can be assigned non-literal values and can be evaluated at runtime. - Mutable During Initialization: The value of a
readonlyfield can be set within the constructor or as part of the field declaration. - Not Implicitly Static: Unlike
const,readonlyfields are not implicitly static. They can be instance-specific. - Flexible Types:
readonlycan be applied to any type, not just primitive data types, enums, and structs. - Thread Safety: Assignment to a
readonlyfield is thread-safe, meaning multiple threads can safely initialize the field without causing race conditions.
Usage Example:
public class ApplicationSettings
{
public readonly string ConfigurationFilePath;
public ApplicationSettings(string path)
{
ConfigurationFilePath = path;
}
// Alternative way to initialize a readonly field
public readonly string DefaultTimeout = "5";
}
public class School
{
public readonly int MaxStudents;
public School(int maxStudents)
{
MaxStudents = maxStudents; // Can be set here
}
}
Important Points:
readonlyprovides immutability after construction, making it suitable for scenarios where the final value might depend on runtime conditions.- It is particularly useful in defining immutable properties of objects when the value might not be determinable until runtime.
Differences Between Const and Readonly
| Criteria | Const | Readonly | |-------------------|---------------------------------------------|-------------------------------------------| | Evaluation Time | Compile Time | Runtime | | Immutability | Value is fixed at compile time | Value is fixed after object construction | | Access | Implicit static (class-level) | Can be instance-specific | | Assignment | Only during declaration | During declaration or in constructor | | Permissible Types | Primitive data types, enums, literal values | Any type |
Scenarios Where to Use Each
Use
constWhen:- The value is known at compile-time.
- You want the value to be embeddable in IL code for performance reasons.
- Multiple classes need access to the same value, and changing it should update it globally.
Use
readonlyWhen:- The value is determined at runtime.
- You need flexibility to assign the value in the constructor.
- The value is specific to an object instance and should not be shared globally.
- You want to ensure that the property remains immutable after construction, which is crucial for thread-safe operations.
Online Code run
Step-by-Step Guide: How to Implement Const and Read Only Keywords in C#
Understanding const and readonly Keywords
1. const Keyword
constis used to declare constants.- Constants are values that, once assigned, cannot be changed throughout the program.
constfields must be initialized at the time of declaration.constcan only contain value types (int,double,char, etc.), strings (System.String), and null references.
2. readonly Keyword
readonlyis used to declare read-only fields.- Read-only fields can have their values set only during object instantiation or inside a constructor of the class.
- They can also be set to a static value during field initialization.
- Unlike
const,readonlycan be used with reference types (including user-defined classes).
Example Scenario
Let's say you are building a software application for a library where you need to define certain fixed constants (like tax or fees) and some values that should not change after an instance is created (like the library name or book ID).
Step-by-Step Examples
Step 1: Using const
Define a Constant
using System;
class LibraryConstants
{
// Defining a constant
public const double LateFeePerDay = 1.50;
public const string LibraryName = "Central Library";
static void Main(string[] args)
{
Console.WriteLine("Library Name: " + LibraryName);
Console.WriteLine("Late Fee Per Day: $" + LateFeePerDay);
// Trying to modify a const value will result in a compile-time error
// LateFeePerDay = 1.75; // Uncommenting this line will cause a compilation error
}
}
Explanation:
const double LateFeePerDay = 1.50;- Declares a constant namedLateFeePerDaywith a value of1.50.const string LibraryName = "Central Library";- Declares a string constant namedLibraryNamewith a value of"Central Library".- You can access these constants using the class name, such as
LibraryConstants.LateFeePerDay. - You cannot change the value of these constants after they are initialized because any attempt to do so will result in a compile-time error.
Output:
Library Name: Central Library
Late Fee Per Day: $1.5
Step 2: Using readonly with Instance Variables
Define a Readonly Field
using System;
class Library
{
// Declaring a readonly instance variable
private readonly string bookId;
// Constructor to initialize readonly variables
public Library(string id)
{
bookId = id;
}
// Method to display the Book ID
public void DisplayBookId()
{
Console.WriteLine("Book ID: " + bookId);
}
static void Main(string[] args)
{
Library myLibrary = new Library("LIB001");
myLibrary.DisplayBookId();
// Trying to modify a readonly field outside its initializer will result in a compile-time error
// myLibrary.bookId = "LIB002"; // Uncommenting this line will cause a compilation error
}
}
Explanation:
private readonly string bookId;- Declares areadonlyinstance variable namedbookId.- The
readonlyvariablebookIdis initialized through the constructorpublic Library(string id). - You can display the value of
bookIdusing theDisplayBookIdmethod. - Once
bookIdis initialized, it cannot be changed outside its initializer (constructor in this case).
Output:
Book ID: LIB001
Step 3: Using readonly with Static Variables
Define a Static Readonly Variable
using System;
class Library
{
// Declaring a readonly static variable
private static readonly string LibraryLocation = "123 Elm Street";
// Constructor
public Library() { }
// Static method to display the Library Location
public static void DisplayLibraryLocation()
{
Console.WriteLine("Library Location: " + LibraryLocation);
}
static void Main(string[] args)
{
Library.DisplayLibraryLocation();
// Trying to modify a static readonly field outside its initializer will result in a compile-time error
// Library.LibraryLocation = "456 Oak Avenue"; // Uncommenting this line will cause a compilation error
}
}
Explanation:
private static readonly string LibraryLocation = "123 Elm Street";- Declares astatic readonlyvariable namedLibraryLocationand initializes it.DisplayLibraryLocationis a static method that accesses thestatic readonlyfieldLibraryLocation.- A
static readonlyvariable can only be modified during field initialization or within a static constructor.
Output:
Library Location: 123 Elm Street
Step 4: Using const and readonly Together
Define Both const and readonly Fields
using System;
class Library
{
// Declaring a static const variable
private static const int MaxBooksPerUser = 5;
// Declaring a static readonly variable
private static readonly DateTime LibraryEstablishedDate = new DateTime(2001, 1, 1);
// Constructor
public Library() { }
// Static method to display maximum books per user and library established date
public static void DisplayLibraryInfo()
{
Console.WriteLine("Maximum Books Per User: " + MaxBooksPerUser);
Console.WriteLine("Library Established Date: " + LibraryEstablishedDate.ToShortDateString());
}
static void Main(string[] args)
{
Library.DisplayLibraryInfo();
// Trying to modify these fields will result in compilation errors
// MaxBooksPerUser = 6; // Uncommenting this line will cause a compilation error
// LibraryEstablishedDate = new DateTime(2010, 1, 1); // Uncommenting this line will cause a compilation error
}
}
Explanation:
private static const int MaxBooksPerUser = 5;- Declares a staticconstvariable namedMaxBooksPerUserwith a static value.private static readonly DateTime LibraryEstablishedDate = new DateTime(...)- Declares a staticreadonlyvariable namedLibraryEstablishedDatewith a date value.DisplayLibraryInfois a static method that displays the values ofMaxBooksPerUserandLibraryEstablishedDate.
Output:
Maximum Books Per User: 5
Library Established Date: 1/1/2001
Key Points to Remember
const:- Used for compile-time constants.
- Can be of primitive data types (int, double, char), strings, or null.
- Must be initialized at the point of declaration.
- Cannot be modified afterward.
- Typically accessed via class name (e.g.,
ClassName.ConstantName).
readonly:- Allows values to be set only once—either during initialization or in a constructor.
- Can be used for both static and instance fields.
- More flexible than
constas it can hold complex data structures (if they are value types like structs). - Useful when the value needs to be determined at runtime but should remain immutable thereafter.
Top 10 Interview Questions & Answers on Const and Read Only Keywords in C#
1. What is the difference between const and readonly in C#?
Answer: The primary difference lies in how and when their values are assigned. const fields must be initialized inline and cannot change value after initialization. They are compile-time constants and are evaluated at compile time, meaning the value is embedded directly into the compiled code. readonly fields must be assigned a value at runtime (either in the constructor or inline) and can only be assigned once, within a constructor or an inline initializer. They are evaluated at runtime.
2. Can const and readonly be used with any type of data?
Answer: const can only be used with value types (like int, double, char, bool, etc.) and string types because these are simple and can be evaluated at compile time. readonly, on the other hand, can be used with any data type, including reference types like classes, structs, and arrays, because their values are determined at runtime.
3. When should you use const instead of readonly?
Answer: Use const when you are dealing with immutable values that are known at compile time and never change. This is beneficial for performance because the constant values are embedded directly into the compiled code. Use readonly when dealing with values that are set at runtime, such as configuration settings or values that are determined through logic, but do not change after the initialization phase.
4. Can const and readonly be used for reference types?
Answer: const cannot be used for reference types other than string. For example, you cannot declare an array as a const. readonly fields can be reference types, arrays, or structs. They provide immutability from the point of view that you cannot assign a new instance to the reference field after it has been initialized, but the contents of the object itself can still be modified unless the object is immutable itself.
5. Can const and readonly fields be used in a static context?
Answer: Yes, both const and readonly can be static fields. const fields are always static by nature, meaning they are shared by all instances of the class. readonly fields can be either instance or static, depending on your needs.
6. What happens if you modify a readonly field after its initial assignment?
Answer: Modifying a readonly field after its initial assignment in the constructor or inline initializer will result in a compile-time error. The readonly keyword ensures that the value can be set only once either at the time of declaration or in a constructor, making the field effectively immutable after this point.
7. Can a const or readonly field be declared without initialization?
Answer: No, a const field must be initialized at the time of declaration. For example, const int myConst; would result in a compile-time error because the compiler requires a value at compile time. A readonly field can be declared without an inline initialization, but it must be set within all constructors of the class.
8. Is there a performance benefit to using const over readonly?
Answer: Yes, there can be a performance benefit to using const over readonly for performance-critical applications. Since const values are embedded directly into the compiled code, access to a const field does not involve a field lookup, which can be more efficient. However, this difference is negligible for most applications.
9. Can const and readonly be used in sealed classes or structs?
Answer: Yes, const and readonly can be used in both sealed classes and structs. The sealed keyword means the class or struct cannot be inherited, but it doesn't affect how const and readonly fields behave within the class or struct.
10. What are the best practices for using const and readonly?
Answer:
- Use
constfor compile-time constants that never change and are used frequently throughout your code. - Use
readonlyfor values that need to be computed or set at runtime but do not change after initialization. - Avoid using
readonlyfor mutable reference types unless you ensure the objects themselves are immutable. - Document your code to clearly indicate the purpose of
constandreadonlyfields for maintainability. - Ensure consistency in your naming conventions to differentiate between mutable and immutable fields.
- Consider the implications of immutability on thread safety and performance.
Login to post a comment.