Bird
Raised Fist0

What will be the output of this C# code?

medium📝 Predict Output Q5 of Q15
C Sharp (C#) - Properties and Encapsulation
What will be the output of this C# code?
class Box {
  private int length;
  public int Length {
    get { return length; }
    private set { length = value; }
  }
  public Box(int len) {
    Length = len;
  }
}

Box b = new Box(10);
Console.WriteLine(b.Length);
A0
BCompilation error
C10
DRuntime exception
Step-by-Step Solution
Solution:
  1. Step 1: Understand private set accessor

    The Length property has a private set, so it can be set inside the class but not outside.
  2. Step 2: Constructor sets Length

    The constructor sets Length = len which is allowed because it's inside the class.
  3. Final Answer:

    10 -> Option C
  4. Quick Check:

    Private set allows internal assignment [OK]
Quick Trick: Private set allows setting only inside class [OK]
Common Mistakes:
MISTAKES
  • Thinking private set causes error outside class
  • Assuming constructor can't set property
  • Confusing private set with no set

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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