Auto-Implemented Properties in C#

What are Auto-Implemented Properties in C#?

Auto-Implemented Properties simplify property declarations by automatically handling the backing field. They provide a clean and concise way to define properties without explicitly declaring private fields.

Key Features of Auto-Implemented Properties

  • Automatically generates a hidden backing field.
  • Reduces boilerplate code and improves readability.
  • Can have get and set accessors.
  • Supports read-only and write-only properties.

Example: Using Auto-Implemented Properties

The following example demonstrates how to declare and use auto-implemented properties.

Example: Auto-Implemented Properties in C#

public class Employee
{
    public string Name { get; set; }
    public int Salary { get; set; }
}

// Usage
class Program
{
    static void Main()
    {
        Employee emp = new Employee { Name = "Alice", Salary = 60000 };
        Console.WriteLine($"Employee: {emp.Name}, Salary: {emp.Salary}");
    }
}

// Output:
// Employee: Alice, Salary: 60000
        

The Name and Salary properties are automatically managed by C#, eliminating the need for explicit field declarations.

Read-Only and Write-Only Auto-Implemented Properties

Auto-implemented properties can be made read-only or write-only using get and set accessors.

Property Type Declaration Usage
Read-Only public string ID { get; } Can be assigned only in the constructor.
Write-Only public string Password { set; } Value can be set but not retrieved.
Read-Write public string Name { get; set; } Value can be assigned and retrieved.

Example: Read-Only Auto-Implemented Property

The following example demonstrates a read-only property using a constructor.

Example: Read-Only Property

public class Product
{
    public string Name { get; }
    public double Price { get; set; }

    public Product(string name, double price)
    {
        Name = name;
        Price = price;
    }
}

// Usage
Product prod = new Product("Laptop", 1200.50);
Console.WriteLine($"Product: {prod.Name}, Price: {prod.Price}");

// prod.Name = "Tablet"; // Error: Cannot assign to read-only property
        

Here, the Name property is assigned only in the constructor, making it immutable after object creation.

Benefits of Auto-Implemented Properties

  • Reduces code verbosity by eliminating explicit field declarations.
  • Improves maintainability by encapsulating data within a class.
  • Enhances readability by keeping property declarations concise.
  • Allows defining immutable objects using get-only properties.