Bird
0
0

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

medium📝 Predict Output Q13 of 15
C Sharp (C#) - Classes and Objects
What will be the output of the following C# code?
class Person {
  public string Name;
  public Person(string name) {
    Name = name;
  }
}

var p = new Person("Anna");
Console.WriteLine(p.Name);
ACompilation error
BAnna
Cnull
DName
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor usage

    The constructor sets the Name field to the passed string "Anna" when creating the Person object.
  2. Step 2: Check output of Console.WriteLine

    Since p.Name was set to "Anna", printing p.Name outputs "Anna".
  3. Final Answer:

    Anna -> Option B
  4. Quick Check:

    Constructor sets Name = "Anna" so output = Anna [OK]
Quick Trick: Constructor sets fields; output shows assigned value [OK]
Common Mistakes:
MISTAKES
  • Assuming default null value instead of assigned
  • Confusing field name with value
  • Expecting compilation error due to constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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