Bird
0
0

What will be the output of the following C# code?

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

var p = new Person();
Console.WriteLine(p.GetName());
AAlice
Bname
CCompilation error
Dnull
Step-by-Step Solution
Solution:
  1. Step 1: Understand private field and public method

    The field name is private but accessible inside the class. The method GetName() returns the value of name.
  2. Step 2: Check the output of calling GetName()

    Calling p.GetName() returns "Alice", which is printed.
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    Private field accessed via public method = Alice [OK]
Quick Trick: Private data accessed through public method returns actual value [OK]
Common Mistakes:
MISTAKES
  • Expecting a compilation error due to private field
  • Thinking it prints the field name 'name'
  • Assuming null because field is private

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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