Bird
Raised Fist0

Which of the following is the correct way to declare a read-only computed property in C#?

easy📝 Syntax Q3 of Q15
C Sharp (C#) - Properties and Encapsulation
Which of the following is the correct way to declare a read-only computed property in C#?
Apublic int Area() => Width * Height;
Bpublic int Area { get => Width * Height; }
Cpublic int Area { get; set; } = Width * Height;
Dpublic int Area { set => Width * Height; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand read-only computed property syntax

    Read-only computed properties have a get accessor that returns a calculated value.
  2. Step 2: Check options

    public int Area { get => Width * Height; } correctly uses get accessor with expression. public int Area { set => Width * Height; } wrongly uses set accessor. public int Area { get; set; } = Width * Height; uses auto-property with initializer, which is not computed. public int Area() => Width * Height; is a method, not a property.
  3. Final Answer:

    public int Area { get => Width * Height; } -> Option B
  4. Quick Check:

    Read-only computed property = get accessor only [OK]
Quick Trick: Use get accessor for read-only computed properties [OK]
Common Mistakes:
MISTAKES
  • Using set accessor in computed property
  • Confusing methods with properties
  • Using auto-properties with initializers incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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