Constants and readonly Fields
Distinguish const from static readonly.
Two Ways to Make Values Fixed
C# offers const and readonly for values that should not change. They look similar but behave very differently. This lesson compares them.
using System;
class Config
{
public const double Pi = 3.14159;
public static readonly DateTime StartedAt = DateTime.Now;
}
class Program
{
static void Main()
{
Console.WriteLine("Pi = " + Config.Pi);
}
}const: Compile-Time Constant
A const must be assigned a literal value at declaration and is baked in at compile time. It is implicitly static.
using System;
class Circle
{
public const double Pi = 3.14159;
public static double Area(double r) => Pi * r * r;
}
class Program
{
static void Main()
{
Console.WriteLine(Circle.Area(2).ToString("0.00"));
}
}All lessons in this course
- Static Methods and Fields
- Static Classes for Utilities
- Constants and readonly Fields
- Static vs Instance Design