Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
C Sharp (C#) - Properties and Encapsulation
What will be the output of this code?
public class Car {
    public string Model { get; init; }
}

var car = new Car { Model = "Tesla" };
Console.WriteLine(car.Model);
Anull
BCompilation error
CTesla
DRuntime exception
Step-by-Step Solution
Solution:
  1. Step 1: Understand property initialization

    The property Model has an init-only setter, so it can be set during object initialization.
  2. Step 2: Analyze the code output

    The object is initialized with Model = "Tesla", so printing car.Model outputs "Tesla".
  3. Final Answer:

    Tesla -> Option C
  4. Quick Check:

    Init-only property set at creation = Tesla [OK]
Quick Trick: Init-only allows setting in initializer, so value prints [OK]
Common Mistakes:
MISTAKES
  • Expecting compilation error for init-only usage
  • Assuming property is null if set in initializer
  • Thinking runtime error occurs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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