Bird
Raised Fist0

What will be the output of the following code?

medium📝 Predict Output Q13 of Q15
C Sharp (C#) - Classes and Objects
What will be the output of the following code?
class Person {
  public string Name;
  public Person(string Name) {
    this.Name = Name;
  }
  public void PrintName() {
    Console.WriteLine(this.Name);
  }
}

var p = new Person("Alice");
p.PrintName();
AName
BCompilation error
CAlice
Dnull
Step-by-Step Solution
Solution:
  1. Step 1: Analyze constructor assignment

    The constructor assigns the parameter Name to the field Name using this.Name = Name;.
  2. Step 2: Check output of PrintName()

    The method prints the field Name, which holds "Alice".
  3. Final Answer:

    Alice -> Option C
  4. Quick Check:

    Constructor sets field, print shows "Alice" [OK]
Quick Trick: Constructor sets field with this, print shows value [OK]
Common Mistakes:
MISTAKES
  • Confusing parameter and field values
  • Expecting default null output
  • Thinking this causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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