Bird
0
0

What will be the output of this C# code?

medium📝 Predict Output Q4 of 15
C Sharp (C#) - Classes and Objects
What will be the output of this C# code?
class Animal {
  public string Name;
  public Animal(string name) {
    Name = name;
  }
}
class Program {
  static void Main() {
    Animal a = new Animal("Cat");
    System.Console.WriteLine(a.Name);
  }
}
AAnimal
BCat
Cnull
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze constructor usage

    The constructor sets Name to the passed string "Cat".
  2. Step 2: Check output statement

    Console.WriteLine prints the Name field, which is "Cat".
  3. Final Answer:

    Cat -> Option B
  4. Quick Check:

    Constructor sets field = B [OK]
Quick Trick: Constructor assigns values; output shows assigned value. [OK]
Common Mistakes:
MISTAKES
  • Assuming default null value instead of assigned
  • Thinking class name prints instead of field
  • Confusing 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