C# Properties - Complete Guide
Introduction to Properties
Properties in C# are members that act as accessors to fields. They allow reading, writing, or computing values while encapsulating the underlying implementation.
They provide a clean syntax for accessing data (similar to fields) but also support validation, computed results, and different accessibility levels.
Types of Properties
C# supports several types of properties, including auto-implemented properties, read-only properties, properties with validation, computed properties, and expression-bodied properties.
Example
using System;
namespace PropertiesExample
{
public class Person
{
private string _name;
private int _age;
private DateTime _birthDate;
public string Email { get; set; }
public string ID { get; }
public string Name
{
get => _name;
set
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("Name cannot be empty");
_name = value;
}
}
public int Age
{
get => _age;
private set
{
if (value < 0 || value > 150)
throw new ArgumentException("Invalid age");
_age = value;
}
}
public int BirthYear => _birthDate.Year;
public bool IsAdult => Age >= 18;
public Person(string id, string name, int age, DateTime birthDate)
{
ID = id;
Name = name;
Age = age;
_birthDate = birthDate;
}
public void UpdateAge(int newAge) => Age = newAge;
public void DisplayInfo()
{
Console.WriteLine($"ID: {ID}");
Console.WriteLine($"Name: {Name}");
Console.WriteLine($"Age: {Age}");
Console.WriteLine($"Birth Year: {BirthYear}");
Console.WriteLine($"Is Adult: {IsAdult}");
Console.WriteLine($"Email: {Email ?? "Not set"}");
}
}
class Program
{
static void Main(string[] args)
{
try
{
Person person = new Person("P001", "Alice", 25, new DateTime(1998, 5, 15));
person.Email = "alice@example.com";
person.DisplayInfo();
Console.WriteLine("\nAfter updating age:");
person.UpdateAge(26);
person.DisplayInfo();
Console.WriteLine("\nTesting validation:");
try
{
person.Name = "";
}
catch (ArgumentException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Console.WriteLine("\nComputed properties:");
Console.WriteLine($"Birth Year: {person.BirthYear}");
Console.WriteLine($"Is Adult: {person.IsAdult}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}
Output
ID: P001 Name: Alice Age: 25 Birth Year: 1998 Is Adult: True Email: alice@example.com After updating age: ID: P001 Name: Alice Age: 26 Birth Year: 1998 Is Adult: True Email: alice@example.com Testing validation: Error: Name cannot be empty Computed properties: Birth Year: 1998 Is Adult: True