Bird
Raised Fist0

What will be the output of the following C# code?

medium📝 Predict Output Q4 of Q15
C Sharp (C#) - Properties and Encapsulation
What will be the output of the following C# code?
class Car {
  private int speed;
  public int Speed {
    get { return speed; }
    set { speed = value; }
  }
}

Car c = new Car();
c.Speed = 50;
Console.WriteLine(c.Speed);
A50
B0
CCompilation error
DNullReferenceException
Step-by-Step Solution
Solution:
  1. Step 1: Understand property assignment

    The Speed property uses set to assign 50 to the private field speed.
  2. Step 2: Understand property retrieval

    The get accessor returns the value of speed, which is 50.
  3. Final Answer:

    50 -> Option A
  4. Quick Check:

    Property set then get returns assigned value [OK]
Quick Trick: Set assigns value; get returns it [OK]
Common Mistakes:
MISTAKES
  • Assuming default 0 is printed
  • Thinking code causes error
  • Confusing property with method call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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