Properties
Properties in C# are members that offer a flexible way to read, write, or compute the values of private fields. They serve as public access points for private member variables, helping to enforce encapsulation by controlling access to the underlying data. Depending on their implementation, properties can be categorized as read-write, read-only, or write-only
Basics of Properties
Properties are defined using the get and set accessors:
- Get Accessor: Returns the property value.
- Set Accessor: Assigns a new value to the property.
Example
using System;
class Person
{
 // Private fields
 private string firstName;
 private string lastName;
 private int age;
  // Constructor to initialize fields
 public Person(string firstName, string lastName, int age)
 {
   this.firstName = firstName;
   this.lastName = lastName;
   this.age = age;
 }
  // Public property for firstName
 public string FirstName
 {
   get { return firstName; }
   set
   {
     if (!string.IsNullOrWhiteSpace(value))
     {
       firstName = value;
     }
     else
     {
       throw new ArgumentException("First name cannot be empty.");
     }
   }
 }
  // Public property for lastName
 public string LastName
 {
   get { return lastName; }
   set
   {
     if (!string.IsNullOrWhiteSpace(value))
     {
       lastName = value;
     }
     else
     {
       throw new ArgumentException("Last name cannot be empty.");
     }
   }
 }
  // Public property for age with validation
 public int Age
 {
   get { return age; }
   set
   {
     if (value >= 0 && value <= 120)
     {
       age = value;
     }
     else
     {
       throw new ArgumentOutOfRangeException("Age must be between 0 and 120.");
     }
   }
 }
  // Read-only property
 public string FullName
 {
   get { return $"{firstName} {lastName}"; }
 }
  // Method to display person details
 public void DisplayDetails()
 {
   Console.WriteLine($"Name: {FullName}, Age: {age}");
 }
}
class Program
{
 static void Main()
 {
   try
   {
     // Creating an object of the Person class
     Person person = new Person("Neha", "Singh", 25);
      // Accessing properties
     Console.WriteLine($"First Name: {person.FirstName}");
     Console.WriteLine($"Last Name: {person.LastName}");
     Console.WriteLine($"Age: {person.Age}");
     Console.WriteLine($"Full Name: {person.FullName}");
      // Modifying properties
     person.FirstName = "Priya";
     person.LastName = "Gupta";
     person.Age = 20;
      // Calling a method to display person details
     person.DisplayDetails();
   }
   catch (Exception ex)
   {
     Console.WriteLine($"Error: {ex.Message}");
   }
 }
}
Explanation of the Example
- Class Definition:
- We define a ‘Person’ class with three private fields: ‘firstName’, ‘lastName’, and ‘age’.
- Constructor:
- The constructor initializes these fields when an object of the ‘Person’ class is created.
- FirstName Property:
- The ‘FirstName’ property has both get and set accessors. The get accessor returns the value of the ‘firstName’ field, while the set accessor assigns a value to the ‘firstName’ field with validation to ensure that it is not empty.
- LastName Property:
- The ‘LastName’ property is structured similarly to the ‘FirstName’ property, providing controlled access and validation for the ‘lastName’ field.
- Age Property:
- The ‘Age’ property includes validation to ensure that the assigned value falls within a reasonable range (0 to 120). If an invalid value is assigned, an exception is thrown.
- FullName Property:
- The ‘FullName’ property is read-only, meaning it only has a get accessor. It concatenates ‘firstName’ and ‘lastName’` to return the full name of the person.
- DisplayDetails Method:
- This method prints the person’s details to the console.
- Main Method:
- In the main method, we create an object called ‘person’ of the ‘Person’ class using the constructor and initialize it with specific values. We access and print the properties of ‘person’. We also modify the properties and call the ‘DisplayDetails’ method to display the person’s updated details.
- Exception handling is included to catch and display any errors that occur during property assignment.
Key Concepts
Encapsulation: Properties encapsulate fields and provide controlled access, ensuring that validation logic is applied when values are retrieved or assigned.
Validation: Properties can incorporate validation logic to ensure that the assigned values are valid and within acceptable ranges.
Read-Only Properties: Read-only properties allow access to computed values without permitting modifications. For instance, the FullName property is read-only and returns the concatenation of the first and last names.
Exception Handling: The example includes basic exception handling to illustrate how errors can be caught and addressed when invalid values are assigned to properties.
