C# > Object-Oriented Programming (OOP) > Encapsulation > Property Accessors (get, set)
Encapsulation with Property Accessors: A Simple `Person` Class
This snippet demonstrates encapsulation using property accessors (get and set) in C#. Encapsulation is a fundamental OOP principle that bundles data (fields) and methods that operate on that data within a single unit (a class), and restricts direct access to some of the object's components. Property accessors allow controlled access to the internal state of an object, providing a way to read (get) and modify (set) the values of private fields.
The `Person` Class
This code defines a `Person` class with two private fields: `_name` (string) and `_age` (int). Public properties `Name` and `Age` provide controlled access to these fields. The `get` accessor returns the value of the corresponding field. The `set` accessor allows modification of the field's value. Notice how the `Age` property includes validation to ensure the age is not negative. This illustrates how property accessors can enforce constraints and maintain data integrity.
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 cannot be negative.");
}
}
}
}
Using the `Person` Class
This `Example` class demonstrates how to use the `Person` class. A `Person` object is created, and its `Name` and `Age` properties are set using the `set` accessors. The values are then retrieved and displayed using the `get` accessors. Attempting to set a negative age will trigger the validation logic within the `Age` property's `set` accessor, preventing an invalid value from being assigned.
public class Example
{
public static void Main(string[] args)
{
Person person = new Person();
person.Name = "Alice";
person.Age = 30;
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
person.Age = -5; // This will trigger the validation in the set accessor.
}
}
Concepts Behind the Snippet
Encapsulation: Bundling data (fields) and methods that operate on that data into a single unit (class) and restricting direct access to the internal state of an object. This promotes data hiding and protects the object's integrity. Property Accessors (get, set): Provide a controlled way to access and modify the private fields of a class. They allow you to add validation logic and perform other actions when reading or writing data, maintaining the object's internal consistency.
Real-Life Use Case
Consider a `BankAccount` class. You might have a `Balance` property. The `get` accessor would return the current balance. The `set` accessor, however, might be made `private` or `protected` to prevent direct modification from outside the class. Instead, operations like `Deposit` and `Withdraw` would be used to modify the balance, ensuring that the business rules for handling money are always followed.
Best Practices
Interview Tip
Be prepared to explain the difference between fields and properties in C#. Understand the importance of encapsulation and how properties contribute to it. Be ready to discuss scenarios where you would use validation logic within a property's `set` accessor.
When to Use Them
Use property accessors whenever you need to control how data is accessed and modified within a class. This is especially important when you need to enforce validation rules, perform calculations, or trigger events when a property's value changes.
Memory Footprint
Properties themselves do not directly impact the memory footprint of an object. The memory is consumed by the underlying fields that the properties access. However, the code within the `get` and `set` accessors can indirectly affect performance and memory usage if it is complex or resource-intensive.
Alternatives
Auto-implemented properties provide a shorthand syntax for simple properties where no additional logic is needed in the `get` or `set` accessors (e.g., `public string Name { get; set; }`). However, if you require validation or other custom behavior, you'll need to use the full property syntax with explicit `get` and `set` accessors.
Pros
Cons
FAQ
-
What is the difference between a field and a property in C#?
A field is a variable that is directly stored within a class. A property is a member that provides controlled access to a field. Properties use `get` and `set` accessors to define how the field's value is read and written, allowing you to add validation and other logic. -
What is an auto-implemented property?
An auto-implemented property is a shorthand syntax for creating a property when you don't need any custom logic in the `get` or `set` accessors. The compiler automatically creates a private backing field for you. Example: `public string Name { get; set; }` -
Can a property be read-only?
Yes, a property can be read-only by providing only a `get` accessor and omitting the `set` accessor. Example: `public string ReadOnlyValue { get { return "Constant Value"; } }`