Bird
Raised Fist0

What will happen if you try to access a private field directly from outside its class in C#?

medium📝 Predict Output Q5 of Q15
C Sharp (C#) - Properties and Encapsulation
What will happen if you try to access a private field directly from outside its class in C#?
AThe field value is set to zero automatically.
BCompilation error occurs.
CThe program runs but prints null.
DThe field value is printed.
Step-by-Step Solution
Solution:
  1. Step 1: Recall access rules for private fields

    Private fields cannot be accessed outside their class.
  2. Step 2: Identify what happens on direct access attempt

    Compiler prevents access, causing a compilation error.
  3. Final Answer:

    Compilation error occurs. -> Option B
  4. Quick Check:

    Private field direct access = Compilation error [OK]
Quick Trick: Private fields cause compile error if accessed outside class [OK]
Common Mistakes:
MISTAKES
  • Expecting runtime error instead of compile error
  • Thinking field prints default value
  • Assuming automatic zero assignment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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