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.
Practice
const and readonly fields in C#?Solution
Step 1: Understand
constbehaviorconstfields are fixed at compile time and cannot be changed later.Step 2: Understand
readonlybehaviorreadonlyfields can be assigned once at runtime, usually in a constructor, and then cannot change.Final Answer:
constvalues are set at compile time and cannot change;readonlyvalues can be set at runtime but only once. -> Option CQuick Check:
constfixed at compile,readonlyset once at runtime [OK]
- Thinking readonly can be changed multiple times
- Confusing when const values are set
- Assuming const can be assigned in constructors
MaxValue with value 100 in C#?Solution
Step 1: Check correct syntax for constant declaration
In C#,constmust be followed by type, then name and value, likeconst int MaxValue = 100;.Step 2: Identify incorrect options
readonlyrequires a type and cannot be declared like a constant;int constis invalid syntax in C#;static readonlyrequires a type and cannot omit it.Final Answer:
const int MaxValue = 100; -> Option BQuick Check:
const syntax = const type name = value; [OK]
- Using 'int const' instead of 'const int'
- Omitting type in readonly declaration
- Confusing const and readonly syntax
class Test {
public readonly int Value;
public Test(int val) {
Value = val;
}
}
class Program {
static void Main() {
var t = new Test(10);
Console.WriteLine(t.Value);
}
}Solution
Step 1: Understand readonly assignment in constructor
ThereadonlyfieldValueis assigned in the constructor withval, which is 10.Step 2: Check output of Console.WriteLine
The program prints the assigned value ofValue, which is 10.Final Answer:
10 -> Option AQuick Check:
readonly set in constructor prints assigned value [OK]
- Assuming readonly defaults to 0 if assigned in constructor
- Thinking readonly cannot be assigned in constructor
- Expecting compilation or runtime errors
class Sample {
public const int Number;
public Sample() {
Number = 5;
}
}Solution
Step 1: Check const assignment rules
constfields must be assigned a value when declared and cannot be assigned later.Step 2: Analyze code assignment
The code tries to assignNumber = 5;inside the constructor, which is invalid forconst.Final Answer:
Cannot assign a value to a const field outside declaration. -> Option AQuick Check:
const must be assigned only at declaration [OK]
- Trying to assign const in constructor
- Confusing const with readonly assignment rules
- Assuming no error in code
Solution
Step 1: Assign fixed tax rate with const
The tax rate never changes, soconstis appropriate forTaxRate.Step 2: Assign discount rate once at object creation
The discount rate can be set once when the object is created, soreadonlyis suitable forDiscountRate.Step 3: Eliminate incorrect options
public readonly double TaxRate = 0.15; public const double DiscountRate; swaps const and readonly incorrectly; public static double TaxRate = 0.15; public double DiscountRate; uses mutable fields; public double TaxRate = 0.15; public readonly double DiscountRate; uses non-const for tax rate.Final Answer:
public const double TaxRate = 0.15; public readonly double DiscountRate; -> Option DQuick Check:
const fixed forever, readonly set once at creation [OK]
- Using readonly for fixed values
- Using const for values set at runtime
- Not understanding when to use static
Ready to prove it?
Pass the test and this pattern moves unknown
