Bird
0
0

What will be the output of this C# code?

medium📝 Predict Output Q13 of 15
C Sharp (C#) - Properties and Encapsulation
What will be the output of this C# code?
class Person {
  private string name = "Alice";
  public string Name {
    get { return name; }
    set { name = value; }
  }
}

var p = new Person();
p.Name = "Bob";
Console.WriteLine(p.Name);
ABob
Bname
CAlice
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand property set operation

    The line p.Name = "Bob"; calls the set accessor, changing the private field name to "Bob".
  2. Step 2: Understand property get operation

    The line Console.WriteLine(p.Name); calls the get accessor, returning the updated value "Bob".
  3. Final Answer:

    Bob -> Option A
  4. Quick Check:

    Property set changes value, get returns updated value [OK]
Quick Trick: Property set changes field; get returns updated value. [OK]
Common Mistakes:
MISTAKES
  • Assuming output is original field value.
  • Confusing field name with property name.
  • Thinking code causes compilation error.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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