C# Properties (Get and Set)

Welcome to The Coding College! In this tutorial, we will explore properties in C#—a powerful way to control access to a class’s fields. Properties allow you to add logic for getting and setting values while maintaining the simplicity of field access.

What Are Properties in C#?

Properties in C# act as wrappers around fields. They let you control how values are read or written without exposing the fields directly. Properties use two special accessors:

  • get: Used to retrieve the value of a property.
  • set: Used to assign a value to the property.

Why Use Properties?

  • To encapsulate data.
  • To validate data during assignment.
  • To make fields read-only or write-only.
  • To avoid exposing internal implementation details.

Defining a Property

Here’s a basic example of defining a property in a class:

public class Person
{
    private string name; // Private field

    // Property to get and set the value of 'name'
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

Accessing Properties

You can access a property like a regular field:

public class Program
{
    public static void Main()
    {
        Person person = new Person();
        person.Name = "Alice";  // Setting the value using 'set'
        Console.WriteLine(person.Name);  // Getting the value using 'get'
    }
}

Output:

Alice

Auto-Implemented Properties

C# allows you to simplify property declarations using auto-implemented properties. These do not require a separate field definition.

Example:

public class Person
{
    public string Name { get; set; } // Auto-implemented property
}

This is equivalent to:

private string name;
public string Name
{
    get { return name; }
    set { name = value; }
}

Read-Only and Write-Only Properties

Read-Only Property

A property can be made read-only by including only a get accessor.

Example:

public class Person
{
    private string name = "Alice";

    public string Name
    {
        get { return name; }
    }
}

public class Program
{
    public static void Main()
    {
        Person person = new Person();
        Console.WriteLine(person.Name);  // Only 'get' is accessible
        // person.Name = "Bob";         // Error: 'set' is not defined
    }
}

Write-Only Property

A property can be made write-only by including only a set accessor.

Example:

public class Person
{
    private string name;

    public string Name
    {
        set { name = value; }
    }

    public void DisplayName()
    {
        Console.WriteLine($"Name: {name}");
    }
}

public class Program
{
    public static void Main()
    {
        Person person = new Person();
        person.Name = "Alice";  // Only 'set' is accessible
        person.DisplayName();
        // Console.WriteLine(person.Name); // Error: 'get' is not defined
    }
}

Property with Validation

You can add validation logic inside the set accessor.

Example:

public class Student
{
    private int age;

    public int Age
    {
        get { return age; }
        set
        {
            if (value > 0)
                age = value;
            else
                Console.WriteLine("Age must be positive!");
        }
    }
}

public class Program
{
    public static void Main()
    {
        Student student = new Student();
        student.Age = 20;  // Valid value
        Console.WriteLine(student.Age);

        student.Age = -5;  // Invalid value
    }
}

Output:

20
Age must be positive!

Expression-Bodied Properties

For simple properties, you can use expression-bodied members for concise syntax.

Example:

public class Circle
{
    private double radius;

    public double Radius
    {
        get => radius;
        set => radius = value > 0 ? value : 0; // Validation
    }

    public double Area => Math.PI * radius * radius; // Read-only property
}

Backing Fields

Properties often use private fields (called backing fields) to store data.

Example:

public class Employee
{
    private decimal salary;

    public decimal Salary
    {
        get { return salary; }
        set
        {
            if (value >= 0)
                salary = value;
            else
                throw new ArgumentException("Salary cannot be negative");
        }
    }
}

Best Practices for Properties

  1. Use auto-implemented properties for simplicity unless validation or additional logic is needed.
  2. Add validation logic in the set accessor when required.
  3. Use expression-bodied properties for concise, read-only members.
  4. Avoid exposing private fields directly; use properties to control access.
  5. Use naming conventions (PascalCase for properties).

Real-World Example

Here’s an example of how properties are used in a real-world application:

public class BankAccount
{
    private decimal balance;

    public string AccountHolder { get; set; }

    public decimal Balance
    {
        get { return balance; }
        private set { balance = value; }
    }

    public void Deposit(decimal amount)
    {
        if (amount > 0)
            Balance += amount;
        else
            Console.WriteLine("Deposit amount must be positive!");
    }

    public void Withdraw(decimal amount)
    {
        if (amount > 0 && amount <= Balance)
            Balance -= amount;
        else
            Console.WriteLine("Invalid withdrawal amount!");
    }
}

public class Program
{
    public static void Main()
    {
        BankAccount account = new BankAccount
        {
            AccountHolder = "John Doe"
        };

        account.Deposit(500);
        Console.WriteLine($"Balance: {account.Balance}");

        account.Withdraw(200);
        Console.WriteLine($"Balance: {account.Balance}");
    }
}

Conclusion

Properties in C# provide a clean and efficient way to control access to the data of a class while adhering to the principles of encapsulation. Whether you’re adding validation, making fields read-only, or simplifying code with auto-implemented properties, properties are a versatile tool for professional-grade programming.

Visit The Coding College for more tutorials and insights into programming and development. Happy coding! 🎉

Leave a Comment