What are const variables?
const variables are often used for storing constant values, like mathematical constants or fixed values. These variables must be assigned a value at the time of declaration and cannot be changed afterward.
They are implicitly static and belong to the type under which they are defined rather than to the instance that is created.
They are accessible using the type name directly and do not require an instance for referential access. const values are evaluated at compile-time and are directly substituted wherever they are used in code. You can only use value types or strings to create constants.
What are readonly variables?
readonly variables can be assigned a value at the time of declaration or within the constructor of the class they belong to. These are instance-specific and can have different values for each instance of a class. The values assigned to readonly variables are evaluated at runtime, allowing for more dynamic behavior based on constructor logic.
You generally use readonly variables for storing values that can vary between instances of a class but should not change after object creation. You can store complex types, including user-defined classes or structures in a readonly variable.
using System;
class SomeComponent
{
// Const field - Compile-time constant
private const double Pi = 3.14159;
// Readonly field - Can be assigned in constructor
private readonly int Year;
// Constructor
public SomeComponent(int year)
{
Year = year;
}
// Method using the constants
public void PrintValues()
{
Console.WriteLine($"The value of Pi is {Pi}");
Console.WriteLine($"The year is {Year}");
}
}
class Program
{
static void Main(string[] args)
{
SomeComponent example = new SomeComponent(2023);
example.PrintValues();
}
}
Summary – Differences between const and readonly in C#
const keyword | readonly keyword |
---|---|
const creates constants, whose value doesn’t change over time | readonly creates fields, whose value can be assigned only inside the constructor |
const variables are static by default and are type specific | readonly variables are not static types, you can can have different values for each instance of a class |
you can only initialize a const type and cannot assign anywhere else | you can declare a readonly variable without a value, but can only be assigned inside a constructor and nowhere else |
You can only create const variables with value types and strings. | readonly variables can be both value types and reference types |
you cannot create const variables in a local scope, they are only instance fields. | readonly variables can only be declared as instance fields. you cannot create readonly variables in local scope |