Bird
0
0

What will happen when you run this code?

medium📝 Predict Output Q13 of 15
C Sharp (C#) - Properties and Encapsulation
What will happen when you run this code?
public class Person {
    public string Name { get; init; }
}

var p = new Person { Name = "Alice" };
p.Name = "Bob";
Console.WriteLine(p.Name);
APrints 'Alice'
BRuntime exception
CPrints 'Bob'
DCompile-time error
Step-by-Step Solution
Solution:
  1. Step 1: Understand init-only property behavior

    The property Name can only be set during object initialization (inside the braces). Setting it later causes a compile error.
  2. Step 2: Analyze the code

    After creating p with Name = "Alice", the code tries to assign p.Name = "Bob" outside initialization, which is invalid.
  3. Final Answer:

    Compile-time error -> Option D
  4. Quick Check:

    Changing init-only after creation = compile error [OK]
Quick Trick: Init-only properties can't be changed after creation [OK]
Common Mistakes:
MISTAKES
  • Assuming property can be changed anytime
  • Expecting runtime error instead of compile error
  • Confusing init-only with readonly fields

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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