Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
C Sharp (C#) - Properties and Encapsulation
What will be the output of this code?
class Book {
  public string Title { get; private set; } = "Unknown";
  public void SetTitle(string title) {
    Title = title;
  }
}

var book = new Book();
book.SetTitle("C# Guide");
Console.WriteLine(book.Title);
AUnknown
Bnull
CCompilation error
DC# Guide
Step-by-Step Solution
Solution:
  1. Step 1: Understand private set accessor

    The Title property has a private set, so it can only be set inside the class.
  2. Step 2: Check method SetTitle usage

    The method SetTitle sets Title to "C# Guide" inside the class, which is allowed.
  3. Step 3: Output the Title property

    Console.WriteLine prints the updated Title value "C# Guide".
  4. Final Answer:

    C# Guide -> Option D
  5. Quick Check:

    Private set allows internal modification [OK]
Quick Trick: Private set allows changes inside class only [OK]
Common Mistakes:
MISTAKES
  • Thinking private set prevents all assignments
  • Expecting default value printed
  • Assuming compilation error due to private set

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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