Static readonly
Learn to define shared constants with static readonly.
Static readonly
static readonly is a class-level shared immutable value determined at runtime. Declaration: public static readonly int Limit = 100;.
Unlike const: it can take runtime values (such as configuration read from a file), the value is not embedded into consumers (safer versioning) and it can be assigned in any static context including the static constructor. Example: public static readonly DateTime Epoch = new DateTime(1970,1,1);.
When to use static readonly?
If the value is determined at runtime but still shared by all instances, static readonly is the right choice. Examples: a default limit read from a file at startup, a table of error codes, or DateTime-based constants.
These cannot be const because they aren't known at compile time. Instance readonly would have each instance carry its own copy, which is wasteful. static readonly serves all instances from a single copy.
Exercise Cache limit
Add public static readonly int Limit = 100; to Cache. In Main, print Cache.Limit.
Show example solution
Add `public static readonly int Limit = 100;` to Cache. In Main write `Console.WriteLine(Cache.Limit);`.
Example solution:
using System;
class Cache
{
public static readonly int Limit = 100;
}
class Program
{
static void Main()
{
Console.WriteLine(Cache.Limit);
}
}
Test yourself
-
Which statement about static readonly is correct?
- static readonly holds a shared immutable value computed at runtime.
- static readonly takes a compile-time value.
- static readonly can differ per instance.
- static readonly cannot be assigned in a constructor.
Show answer
static readonly holds a shared immutable value computed at runtime. — Correct. static readonly is a shared immutable value determined at runtime.
-
Match: static readonly properties
- sharing
- class level
- value time
- runtime
- versioning
- safe
- instance copy
- none
-
Fill in the blank: static readonly
class Cache { public ____ int Limit = 100; }Show answer
class Cache { public static readonly int Limit = 100; }