Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q14 of 15
C Sharp (C#) - Properties and Encapsulation
Identify the error in this code snippet:
public class Car {
    public string Model { get; init; }
}

var car = new Car();
car.Model = "Sedan";
AMissing constructor call
BProperty Model must have a setter, not init
CCannot assign init-only property outside object initializer
DNo error, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Check how init-only properties are set

    Init-only properties must be set during object creation using an initializer, not after.
  2. Step 2: Analyze the code

    The code creates car with default constructor, then tries to set Model property outside initialization, which is invalid.
  3. Final Answer:

    Cannot assign init-only property outside object initializer -> Option C
  4. Quick Check:

    Init-only set only in initializer, not later [OK]
Quick Trick: Set init-only properties inside braces only [OK]
Common Mistakes:
MISTAKES
  • Trying to set init-only property after creation
  • Thinking init-only means readonly
  • Ignoring object initializer syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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