Bird
0
0

Consider the following code snippet:

medium📝 Predict Output Q13 of 15
C Sharp (C#) - Classes and Objects

Consider the following code snippet:

class MyClass {
    private int secret = 42;
    public int GetSecret() {
        return secret;
    }
}

MyClass obj = new MyClass();
Console.WriteLine(obj.secret);

What will happen when this code runs?

ARuntime error: NullReferenceException
BIt prints 42
CCompilation error: 'secret' is inaccessible due to its protection level
DIt prints 0
Step-by-Step Solution
Solution:
  1. Step 1: Identify access modifier of 'secret'

    The field secret is declared private, so it cannot be accessed outside MyClass.
  2. Step 2: Check code accessing 'secret'

    The code tries to access obj.secret outside the class, which is not allowed and causes a compile-time error.
  3. Final Answer:

    Compilation error: 'secret' is inaccessible due to its protection level -> Option C
  4. Quick Check:

    Private fields cannot be accessed outside class [OK]
Quick Trick: Private members cannot be accessed from outside their class [OK]
Common Mistakes:
MISTAKES
  • Assuming private fields are accessible outside class
  • Confusing runtime errors with compile errors
  • Thinking public methods expose private fields directly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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