In C#, const
, readonly
, and static
are keywords used to define different kinds of members with distinct purposes and behaviors. Here’s an explanation of the differences, along with examples:
1. const
(Constant)
Definition: Used to declare a compile-time constant. Its value is fixed and cannot be changed after compilation.
Scope: Implicitly static
; accessed using the class name, not instance.
Initialization: Must be initialized at the time of declaration.
Use Case: For values that are known at compile-time and will never change.
public class Example { public const double Pi = 3.14159; // Compile-time constant } // Usage: double circumference = 2 * Example.Pi * radius;
Key Points
const
fields are alwaysstatic
.- Only primitive types,
string
, orenum
can beconst
.
YouTube
2. readonly
Definition: Used to declare a runtime constant. Its value is set either at declaration or in the constructor, and cannot be modified thereafter.
Scope: Not implicitly static
; can be either instance-level or static.
Initialization: Can be initialized at declaration or in a constructor.
Use Case: For values that are constant after the object is created but depend on runtime calculations or logic.
public class Example { public readonly double CircleRadius; // Runtime constant public static readonly double Gravity = 9.8; // Static readonly public Example(double radius) { CircleRadius = radius; // Initialized in constructor } } // Usage: var example = new Example(5); Console.WriteLine(example.CircleRadius); // Prints: 5 Console.WriteLine(Example.Gravity); // Prints: 9.8
Key Points
readonly
fields are not implicitlystatic
but can be explicitly declared asstatic
.- Values can be set in the constructor for instance fields.
More C# Ques-Ans
3. static
Definition: Used to declare members or methods that belong to the class rather than any instance of the class.
Scope: Shared among all instances of the class.
Initialization: Can be initialized at declaration or within a static constructor
.
Use Case: For values or methods that are shared across all instances of a class.
public class Example { public static int Counter = 0; // Shared across all instances public Example() { Counter++; } } // Usage: var obj1 = new Example(); var obj2 = new Example(); Console.WriteLine(Example.Counter); // Prints: 2
Key Points
static
fields and methods are accessed using the class name.static
methods cannot access instance members directly.- A
static
constructor initializesstatic
members and is executed only once, when the class is first used.
Practical Differences
- Use
const
for values likePi = 3.14159
orSpeedOfLight = 299792458
that are universal and unchanging. - Use
readonly
for values that depend on runtime conditions (e.g.,StartupTime
or a configuration value). - Use
static
for counters, caches, or methods likeMath.Pow()
that don’t require instance data.