C# Properties (Get and Set)

C# Properties (Get and Set)

Properties in C# provide controlled access to class fields.
They are special methods called getters and setters that allow you to read and write data safely.


🔹 Basic Property Syntax



 


🔹 Auto-Implemented Properties

Simpler syntax without explicit field:



 


🔹 Read-Only Property

Use only get to make property read-only:



 

✔ Can be initialized in constructor.


🔹 Write-Only Property

Use only set to make property write-only:



 


🔹 Property with Logic

You can add validation or computation in get/set:


 


🔹 Expression-Bodied Properties (C# 6+)



 


🔹 Benefits of Properties

✔ Encapsulate fields
✔ Add validation logic
✔ Control read/write access
✔ Improve code readability


🔹 Common Mistakes

❌ Making fields public instead of properties
❌ Forgetting to use value in setter
❌ Accessing private fields directly from outside


🔹 Summary

  • Properties are accessors for fields

  • Use get to read and set to write

  • Supports validation, read-only, write-only, computed values

  • Auto-implemented properties simplify code

You may also like...