Bird
0
0

Consider the following code:

medium📝 Predict Output Q5 of 15
C Sharp (C#) - Properties and Encapsulation
Consider the following code:
public class User {
    public string Username { get; init; }
}

var user = new User { Username = "John" };
user.Username = "Jane";

What will happen when this code runs?
ACompilation error on the second assignment
BUsername changes to "Jane" successfully
CRuntime exception is thrown
DThe initial value "John" is retained silently
Step-by-Step Solution
Solution:
  1. Step 1: Understand init-only property behavior

    Properties with init can only be assigned during object initialization (e.g., in object initializer or constructor).
  2. Step 2: Analyze the code

    The first assignment Username = "John" is valid during initialization. The second assignment user.Username = "Jane"; occurs after initialization, which is not allowed.
  3. Step 3: Result

    This causes a compilation error because the property cannot be assigned outside initialization.
  4. Final Answer:

    Compilation error on the second assignment -> Option A
  5. Quick Check:

    Init-only properties disallow post-initialization assignment [OK]
Quick Trick: Init-only properties can't be set after creation [OK]
Common Mistakes:
MISTAKES
  • Assuming init properties behave like set properties
  • Expecting runtime exceptions instead of compile errors
  • Thinking the value silently ignores changes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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