Property Accessors in C#
What are Property Accessors in C#?
Property Accessors in C# define how properties interact with fields. They include get
and set
accessors to control data access and modification.
Key Features of Property Accessors
- Encapsulate fields within properties for controlled access.
get
accessor retrieves the value of a property.set
accessor assigns a value to a property.- Supports read-only, write-only, and read-write properties.
Example: Using Get and Set Accessors
The following example demonstrates how to define and use property accessors.
Example: Get and Set Accessors in C#
public class Person
{
private string name;
private int age;
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set
{
if (value > 0)
age = value;
else
Console.WriteLine("Age must be positive.");
}
}
}
// Usage
class Program
{
static void Main()
{
Person person = new Person();
person.Name = "Alice";
person.Age = 25;
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
// Output:
// Name: Alice, Age: 25
The Name
and Age
properties allow controlled access to the private fields with validation in the set
accessor.
Read-Only and Write-Only Properties
Properties can be restricted to read-only or write-only based on accessor definitions.
Property Type | Declaration | Usage |
---|---|---|
Read-Only | public int ID { get; } |
Can be assigned only in the constructor. |
Write-Only | public string Password { set; } |
Value can be set but not retrieved. |
Read-Write | public string Name { get; set; } |
Value can be assigned and retrieved. |
Example: Read-Only Property
A read-only property can be set only in the constructor.
Example: Read-Only Property
public class Product
{
public string Name { get; }
public double Price { get; set; }
public Product(string name, double price)
{
Name = name;
Price = price;
}
}
// Usage
Product prod = new Product("Laptop", 1200.50);
Console.WriteLine($"Product: {prod.Name}, Price: {prod.Price}");
// prod.Name = "Tablet"; // Error: Cannot assign to read-only property
The Name
property is set only in the constructor, making it immutable after object creation.
Expression-Bodied Properties (C# 6+)
C# 6+ allows expression-bodied property definitions for simplicity.
Example: Expression-Bodied Property
public class Circle
{
public double Radius { get; set; }
public double Area => Math.PI * Radius * Radius;
}
// Usage
Circle c = new Circle { Radius = 5 };
Console.WriteLine($"Area: {c.Area}"); // Output: Area: 78.54
The Area
property uses an expression-bodied member for cleaner syntax.
Benefits of Property Accessors
- Encapsulates fields while allowing controlled access.
- Enhances data validation using the
set
accessor. - Supports immutability with read-only properties.
- Reduces boilerplate code with auto-implemented and expression-bodied properties.