Swipe
SwipeSwipe
Swipe Apps

Paths

Motivation

Information

Constants & Type Casting · Lesson 26 of 27

Constants (const & readonly)

A free lesson from Swipe Coding · C#, level 2 · updated October 2026

By the Swipe team, founded by Colin · how we make lessons

🤖
Some values should just never change — const makes that a promise. 🔒

Sometimes a value should never change once it's set — think of the number of days in a week, or the maximum number of players allowed in a game. C# lets you mark a variable as a compile-time constant using the const keyword, which tells the compiler this value must never change, and must be fully known before the program even runs.

const double Pi = 3.14159;
Console.WriteLine(Pi);
Declaring a constant with const — Pi can be read, but never reassigned.

A const has to be assigned a value right where it is declared, and that value must be something the compiler can work out immediately — a fixed number, string, or simple expression. You can't use const for something that is only known once the program is running, such as the current time or a value typed in by a user.

Fill in the blank

The ____ keyword marks a variable as a value that must be known at compile time and can never change.

🤖
readonly is const's more flexible cousin. 🧩

For a value that must never change but is only known once the program starts running — such as a timestamp — C# offers a second keyword: readonly. A readonly field can be assigned once, either where it is declared or inside the class's constructor (which you will meet soon), and after that its value is locked in for good. Unlike const, readonly can only be used on fields that belong to a class, not on local variables inside a method.

class Program
{
    static readonly DateTime StartedAt = DateTime.Now;

    static void Main()
    {
        Console.WriteLine(StartedAt);
    }
}
StartedAt is fixed once the program starts, even though DateTime.Now could never be known at compile time.
🤖
This one small capitalization choice sets C# apart from a lot of other languages. 🔠

By convention, constant names in C# are written in PascalCase — every word capitalized, with no underscores, such as MaxPlayers or DaysInWeek. This matches the same PascalCase style used for class names, and instantly marks a name as a constant or fixed value to anyone reading the code.

const int MaxPlayers = 4;
Console.WriteLine(MaxPlayers);
MaxPlayers follows the PascalCase convention that C# developers use for constants.
Quick check

What is the key difference between const and readonly in C#?

True or false

A const field can be assigned a value that is only known while the program is running, such as DateTime.Now.

Keep your streak going in Swipe Coding

Swipe through every level of C# on your iPhone — with XP, stars, streaks, a personal advisor and the full track beyond these free levels.

Get the Swipe apps →