Bird
Raised Fist0

What is wrong with this C# class?

medium📝 Debug Q7 of Q15
C Sharp (C#) - Classes and Objects
What is wrong with this C# class?
class Employee {
  public string name;
  public void Employee(string n) {
    name = n;
  }
}
AThe field name is private by default
BThe method Employee looks like a constructor but has a void return type
CThe class is missing a semicolon after the closing brace
DThe class cannot have methods with parameters
Step-by-Step Solution
Solution:
  1. Step 1: Identify constructor syntax

    Constructors must not have a return type, not even void.
  2. Step 2: Analyze the method

    Here, Employee is declared as void, so it's a method, not a constructor.
  3. Step 3: Consequence

    No constructor exists, so default constructor is used; intended initialization won't happen.
  4. Final Answer:

    The method Employee looks like a constructor but has a void return type -> Option B
  5. Quick Check:

    Constructors have no return type [OK]
Quick Trick: Constructors never specify a return type [OK]
Common Mistakes:
MISTAKES
  • Thinking methods can have the same name as class with void
  • Assuming fields are private by default
  • Believing semicolon is needed after class brace

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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