C# > Object-Oriented Programming (OOP) > Encapsulation > Private Fields and Public Methods
Encapsulation with Properties: Person Class
This example illustrates encapsulation using properties in C#. It demonstrates how to protect fields while still providing a way to access and modify them through controlled accessors (getters and setters).
Code Snippet
The Person
class has two private fields: _name
and _age
. Instead of providing direct access to these fields, we define public properties Name
and Age
. The get
accessor in each property returns the value of the corresponding private field. The set
accessor allows setting the value, but includes validation logic to ensure that the new value is valid (e.g., the name is not empty and the age is within a reasonable range). This prevents invalid data from being assigned to the fields.
public class Person
{
private string _name;
private int _age;
public string Name
{
get { return _name; }
set
{
if (!string.IsNullOrEmpty(value))
{
_name = value;
}
else
{
Console.WriteLine("Name cannot be empty.");
}
}
}
public int Age
{
get { return _age; }
set
{
if (value >= 0 && value <= 150)
{
_age = value;
}
else
{
Console.WriteLine("Invalid age value.");
}
}
}
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
public class Example
{
public static void Main(string[] args)
{
Person person = new Person("John Doe", 30);
Console.WriteLine("Name: " + person.Name);
Console.WriteLine("Age: " + person.Age);
person.Age = 35;
Console.WriteLine("Updated Age: " + person.Age);
person.Age = -5; // This will trigger the validation.
}
}
Concepts Behind the Snippet
Properties are a C# language feature that provide a convenient way to implement encapsulation. They act as intermediaries between the private fields and the outside world, allowing you to control how the fields are accessed and modified. Properties are essentially special methods that look like fields when used, making the code more readable and maintainable. The get
and set
accessors provide fine-grained control over the access and modification of the underlying data.
Real-Life Use Case
Consider a scenario where you're building an e-commerce application. You might have a Product
class with a Price
property. Using encapsulation, you can ensure that the price is always a positive value and that any discounts applied are within acceptable limits. The set
accessor of the Price
property can implement these validations, preventing invalid price values from being stored.
Best Practices
set
accessor of properties to ensure data integrity.get
accessor of properties.public string Address { get; set; }
).
Interview Tip
When explaining properties, highlight the benefits of using them over direct field access. Emphasize their role in encapsulation, data validation, and code readability. Be prepared to discuss the differences between auto-implemented properties and properties with explicit get
and set
accessors.
When to Use Them
Use properties whenever you need to expose data from a class in a controlled manner. They are especially useful when you need to implement validation logic or perform other operations when the data is accessed or modified. If you don't need any special logic, use auto-implemented properties for simplicity.
Memory Footprint
Properties themselves do not add any significant memory overhead. The memory footprint is primarily determined by the data types of the underlying private fields.
Alternatives
Instead of properties, you could use separate Get
and Set
methods. However, properties provide a more concise and readable syntax, making them the preferred approach in most C# code.
Pros
Cons
FAQ
-
What is the difference between a field and a property?
A field is a variable that stores data within a class. A property is a member that provides a controlled way to access and modify a field. Properties useget
andset
accessors to define how the field is accessed and modified, allowing you to implement validation and other logic. -
What are auto-implemented properties?
Auto-implemented properties are a shorthand way to define properties when you don't need to add any custom logic to theget
andset
accessors. The compiler automatically creates a backing field for the property. -
Can I have a read-only property?
Yes, you can create a read-only property by providing only aget
accessor and noset
accessor. This prevents the property from being modified from outside the class.