Bird
0
0

What will happen if you try to compile this code?

medium📝 Predict Output Q5 of 15
C Sharp (C#) - Classes and Objects
What will happen if you try to compile this code?
class Sample {
  int number;
}

class Program {
  static void Main() {
    Sample s = new Sample();
    Console.WriteLine(s.number);
  }
}
APrints 0
BCompilation error due to inaccessible field
CRuntime error
DPrints null
Step-by-Step Solution
Solution:
  1. Step 1: Check access modifier of 'number'

    The field number has no access modifier, so it is private by default.
  2. Step 2: Understand access from Main method

    The Main method tries to access s.number, which is private and inaccessible, causing a compilation error.
  3. Final Answer:

    Compilation error due to inaccessible field -> Option B
  4. Quick Check:

    Private field access outside class = compilation error [OK]
Quick Trick: Fields without access modifier are private by default [OK]
Common Mistakes:
MISTAKES
  • Assuming default is public
  • Expecting runtime error
  • Thinking it prints 0 automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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