Bird
0
0

Find the problem in this code:

medium📝 Debug Q7 of 15
C Sharp (C#) - Properties and Encapsulation
Find the problem in this code:
public class Employee {
    public string Id { get; init; }
}

var emp = new Employee();
emp.Id = "E123";
emp.Id = "E456";
AProperty Id must be readonly to prevent changes.
BCannot assign to 'Id' after object creation; second assignment causes error.
CMultiple assignments to init-only property are allowed.
DNo error; code works as expected.
Step-by-Step Solution
Solution:
  1. Step 1: Recall init-only setter rules

    Init-only properties can only be assigned once during initialization.
  2. Step 2: Analyze assignments

    First assignment after creation is invalid, causing compile error; second assignment is unreachable.
  3. Final Answer:

    Cannot assign to 'Id' after object creation; second assignment causes error. -> Option B
  4. Quick Check:

    Init-only disallows assignments after creation [OK]
Quick Trick: Init-only properties accept only one assignment during creation [OK]
Common Mistakes:
MISTAKES
  • Assuming multiple assignments are allowed
  • Confusing init-only with readonly
  • Ignoring compile-time errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes