Constants and readonly fields let you store values that should not change after you set them. This helps keep your program safe and clear.
Constants and readonly fields in C Sharp (C#)
public const int DaysInWeek = 7; public readonly int MaxUsers; public MyClass() { MaxUsers = 100; }
const values must be set when declared and cannot change later.
readonly fields can be set when declared or inside a constructor, but not changed after that.
public const double Pi = 3.14159;
public readonly string ConnectionString; public MyClass() { ConnectionString = "Server=localhost;Database=myDb;"; }
public const int MaxScore = 100; // MaxScore = 200; // This will cause an error because const cannot be changed.
This program shows how to use a constant and a readonly field. The constant is fixed at 7, and the readonly field is set when the object is created.
using System; class Program { public const int DaysInWeek = 7; public readonly int MaxPlayers; public Program(int maxPlayers) { MaxPlayers = maxPlayers; } public void ShowInfo() { Console.WriteLine($"Days in a week: {DaysInWeek}"); Console.WriteLine($"Max players allowed: {MaxPlayers}"); } static void Main() { Program game = new Program(5); game.ShowInfo(); } }
Use const for values that never change and are known at compile time.
Use readonly when the value is set once but only known at runtime, like from a constructor.
Trying to change a const or readonly value after initialization will cause errors.
const means the value is fixed forever and set when declared.
readonly means the value can be set once, usually in a constructor, and then stays the same.
Both help keep your program safe by preventing unwanted changes.