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}");
}
}
}
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.