Bird
Raised Fist0

Which of the following is the correct syntax for a read-only computed property in C#?

easy📝 Syntax Q12 of Q15
C Sharp (C#) - Properties and Encapsulation
Which of the following is the correct syntax for a read-only computed property in C#?
Apublic int Total() { return Price + Quantity; }
Bpublic int Total { get { return Price * Quantity; } }
Cpublic int Total => Price + Quantity { get; set; }
Dpublic int Total { set { Price = value; } }
Step-by-Step Solution
Solution:
  1. Step 1: Identify read-only computed property syntax

    public int Total { get { return Price * Quantity; } } uses a property with only a get accessor returning a calculation, which is correct.
  2. Step 2: Check other options for errors

    public int Total { set { Price = value; } } only has set, so not read-only. public int Total => Price + Quantity { get; set; } mixes expression body with get/set incorrectly. public int Total() { return Price + Quantity; } is a method, not a property.
  3. Final Answer:

    public int Total { get { return Price * Quantity; } } -> Option B
  4. Quick Check:

    Read-only computed property = get only [OK]
Quick Trick: Read-only properties have only get accessor [OK]
Common Mistakes:
MISTAKES
  • Using set accessor in read-only properties
  • Confusing methods with properties
  • Incorrect expression body syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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