Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Constants and readonly fields in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Constants and readonly fields
Declare constant with 'const'
↓
Value fixed at compile time
↓
Use constant anywhere
↓
Declare readonly field with 'readonly'
↓
Value set at declaration or in constructor
↓
Value fixed after construction
↓
Use readonly field anywhere
Constants are fixed values set at compile time. Readonly fields can be set once during object creation and then stay fixed.
Execution Sample
C Sharp (C#)
class Example {
  public const int DaysInWeek = 7;
  public readonly int Year;
  public Example(int year) {
    Year = year;
  }
}
Defines a constant for days in a week and a readonly field for the year set during object creation.
Execution Table
StepActionValue AssignedWhen AssignedCan Change Later?
1Declare const DaysInWeek7Compile timeNo
2Declare readonly Year fieldunassignedN/AYes, once in constructor
3Create Example object with year=2024Year = 2024ConstructorNo
4Try to change DaysInWeekErrorN/ANo
5Try to change Year after constructionErrorN/ANo
💡 Constants fixed at compile time; readonly fields fixed after constructor; attempts to change cause errors.
Variable Tracker
VariableStartAfter DeclarationAfter ConstructorFinal
DaysInWeekN/A777
YearN/Aunassigned20242024
Key Moments - 3 Insights
Why can't I assign a value to a const variable inside a constructor?
Constants are fixed at compile time and must be assigned where declared, not in constructors. See execution_table step 1 vs step 3.
Can I change a readonly field after the object is created?
No, readonly fields can only be assigned once during declaration or in the constructor. After that, they cannot be changed. See execution_table step 5.
Why does trying to change a const or readonly variable cause an error?
Because const values are fixed at compile time and readonly fields are fixed after construction, the compiler prevents changes to keep data safe. See execution_table steps 4 and 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of DaysInWeek after declaration?
A0
B7
Cunassigned
DCannot be assigned
💡 Hint
Check execution_table row 1 and variable_tracker for DaysInWeek after declaration.
At which step does the readonly field Year get its value?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table step 3 where Year is assigned in the constructor.
If you try to change Year after construction, what happens according to the execution_table?
AError occurs
BValue changes successfully
CValue resets to default
DValue becomes null
💡 Hint
See execution_table step 5 about changing Year after construction.
Concept Snapshot
const: fixed value at compile time, assigned where declared
readonly: assigned once at declaration or in constructor
const cannot be changed anywhere
readonly can be set only during construction
both provide safety for fixed data
Full Transcript
This lesson shows how constants and readonly fields work in C#. Constants are values fixed at compile time and must be assigned where declared. Readonly fields can be assigned once either at declaration or inside the constructor. After that, readonly fields cannot be changed. The execution table traces declaring a const DaysInWeek with value 7, declaring a readonly Year field, assigning Year in the constructor, and shows errors if you try to change these values later. The variable tracker shows DaysInWeek is always 7 and Year is assigned 2024 during construction. Key moments clarify why const cannot be assigned in constructors and why readonly fields cannot be changed after construction. The quiz tests understanding of when values are assigned and what happens if you try to change them. Remember, const is for fixed compile-time values, readonly is for values fixed after object creation.

Practice

(1/5)
1. What is the main difference between const and readonly fields in C#?
easy
A. const and readonly are exactly the same and can be used interchangeably.
B. readonly values are set at compile time and cannot change; const values can be set at runtime but only once.
C. const values are set at compile time and cannot change; readonly values can be set at runtime but only once.
D. const values can be changed anytime; readonly values cannot be changed.

Solution

  1. Step 1: Understand const behavior

    const fields are fixed at compile time and cannot be changed later.
  2. Step 2: Understand readonly behavior

    readonly fields can be assigned once at runtime, usually in a constructor, and then cannot change.
  3. Final Answer:

    const values are set at compile time and cannot change; readonly values can be set at runtime but only once. -> Option C
  4. Quick Check:

    const fixed at compile, readonly set once at runtime [OK]
Hint: Remember: const fixed early, readonly set once later [OK]
Common Mistakes:
  • Thinking readonly can be changed multiple times
  • Confusing when const values are set
  • Assuming const can be assigned in constructors
2. Which of the following is the correct way to declare a constant integer named MaxValue with value 100 in C#?
easy
A. readonly int MaxValue = 100;
B. const int MaxValue = 100;
C. int const MaxValue = 100;
D. static readonly MaxValue = 100;

Solution

  1. Step 1: Check correct syntax for constant declaration

    In C#, const must be followed by type, then name and value, like const int MaxValue = 100;.
  2. Step 2: Identify incorrect options

    readonly requires a type and cannot be declared like a constant; int const is invalid syntax in C#; static readonly requires a type and cannot omit it.
  3. Final Answer:

    const int MaxValue = 100; -> Option B
  4. Quick Check:

    const syntax = const type name = value; [OK]
Hint: const must include type before name [OK]
Common Mistakes:
  • Using 'int const' instead of 'const int'
  • Omitting type in readonly declaration
  • Confusing const and readonly syntax
3. What will be the output of the following C# code?
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);
    }
}
medium
A. 10
B. 0
C. Compilation error
D. Runtime error

Solution

  1. Step 1: Understand readonly assignment in constructor

    The readonly field Value is assigned in the constructor with val, which is 10.
  2. Step 2: Check output of Console.WriteLine

    The program prints the assigned value of Value, which is 10.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    readonly set in constructor prints assigned value [OK]
Hint: readonly can be set once in constructor, then used [OK]
Common Mistakes:
  • Assuming readonly defaults to 0 if assigned in constructor
  • Thinking readonly cannot be assigned in constructor
  • Expecting compilation or runtime errors
4. Identify the error in the following C# code:
class Sample {
    public const int Number;
    public Sample() {
        Number = 5;
    }
}
medium
A. Cannot assign a value to a const field outside declaration.
B. Const fields must be assigned in constructor, not declaration.
C. Const fields can be assigned multiple times.
D. No error, code is correct.

Solution

  1. Step 1: Check const assignment rules

    const fields must be assigned a value when declared and cannot be assigned later.
  2. Step 2: Analyze code assignment

    The code tries to assign Number = 5; inside the constructor, which is invalid for const.
  3. Final Answer:

    Cannot assign a value to a const field outside declaration. -> Option A
  4. Quick Check:

    const must be assigned only at declaration [OK]
Hint: const value fixed at declaration, not in constructor [OK]
Common Mistakes:
  • Trying to assign const in constructor
  • Confusing const with readonly assignment rules
  • Assuming no error in code
5. You want to create a class that stores a fixed tax rate that never changes and a discount rate that can be set once when the object is created but never changed after. Which declarations are correct in C#?
hard
A. public double TaxRate = 0.15; public readonly double DiscountRate;
B. public readonly double TaxRate = 0.15; public const double DiscountRate;
C. public static double TaxRate = 0.15; public double DiscountRate;
D. public const double TaxRate = 0.15; public readonly double DiscountRate;

Solution

  1. Step 1: Assign fixed tax rate with const

    The tax rate never changes, so const is appropriate for TaxRate.
  2. Step 2: Assign discount rate once at object creation

    The discount rate can be set once when the object is created, so readonly is suitable for DiscountRate.
  3. 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.
  4. Final Answer:

    public const double TaxRate = 0.15; public readonly double DiscountRate; -> Option D
  5. Quick Check:

    const fixed forever, readonly set once at creation [OK]
Hint: Use const for fixed, readonly for one-time set [OK]
Common Mistakes:
  • Using readonly for fixed values
  • Using const for values set at runtime
  • Not understanding when to use static
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard