C# > Object-Oriented Programming (OOP) > Classes and Objects > Class Declaration

Class with Properties in C#

This snippet extends the basic class declaration by incorporating properties, which provide controlled access to the class's data. Properties allow you to add logic when reading or writing to a field, enforcing validation and encapsulation.

Class with Properties

This code defines a `Person` class with a private field `_name` and a corresponding property `Name`. The `get` accessor returns the value of `_name`. The `set` accessor includes validation logic to ensure that the name is not empty. If the provided value is valid, it updates the `_name` field; otherwise, it prints an error message. The `Age` property is an auto-implemented property, which means that the compiler automatically generates the backing field and the `get` and `set` accessors.

public class Person
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set
        {
            if (!string.IsNullOrEmpty(value))
            {
                _name = value;
            }
            else
            {
                Console.WriteLine("Name cannot be empty.");
            }
        }
    }

    public int Age { get; set; } // Auto-implemented property

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void DisplayPersonInfo()
    {
        Console.WriteLine($"Name: {Name}, Age: {Age}");
    }
}

Concepts Behind the Snippet

Properties: Properties provide controlled access to a class's data. They consist of `get` and `set` accessors. The `get` accessor is used to retrieve the value of a property, and the `set` accessor is used to set the value of a property. Encapsulation: Properties enhance encapsulation by allowing you to control how data is accessed and modified. Auto-Implemented Properties: These are a shorthand way to declare properties when you don't need to add any custom logic to the `get` or `set` accessors. The compiler automatically creates the backing field.

Real-Life Use Case

Consider a user profile in a social media application. The `Person` class could represent a user, and properties like `Name`, `Email`, and `Password` could be used to store user information. The `set` accessors could include validation logic to ensure that the email is in a valid format or that the password meets certain security requirements.

Best Practices

  • Validation: Always validate input in the `set` accessors of properties to ensure data integrity.
  • Read-Only Properties: If a property should only be readable, you can omit the `set` accessor, making it read-only.
  • Naming Conventions: Property names should be PascalCase (e.g., `Name`, `Age`). Backing fields are conventionally named with a leading underscore (e.g., `_name`).

Interview Tip

Explain why properties are preferred over directly exposing fields. Emphasize the benefits of encapsulation, data validation, and the ability to change the implementation without breaking dependent code.

When to Use Properties

Use properties whenever you need to control access to a class's data. Properties provide a way to encapsulate data and add logic to the process of reading and writing values. They are essential for maintaining data integrity and flexibility in your code.

Memory Footprint

Properties themselves don't directly add to the memory footprint of the class. The backing fields used to store the data are what consume memory. The size of the memory footprint depends on the data types of the backing fields.

Alternatives

While properties are the standard way to control access to data in C#, you could technically use methods (e.g., `GetName()`, `SetName()`) to achieve similar results. However, properties provide a more concise and idiomatic syntax.

Pros

  • Encapsulation: Properties provide a way to encapsulate data and control access to it.
  • Data Validation: Properties allow you to add validation logic to ensure data integrity.
  • Flexibility: You can change the implementation of a property without breaking dependent code.

Cons

  • Slight Overhead: There is a slight overhead associated with calling a property's `get` or `set` accessor compared to directly accessing a field. However, this overhead is usually negligible.
  • Increased Code: Properties require more code than directly exposing fields, especially if you need to add custom logic to the accessors.

FAQ

  • What is the purpose of properties?

    Properties provide controlled access to a class's data, allowing you to encapsulate data and add logic to the process of reading and writing values.
  • What is the difference between a field and a property?

    A field is a variable that stores data directly within a class. A property is a member that provides controlled access to a field. Properties include `get` and `set` accessors, which allow you to add logic when reading or writing to the underlying field.
  • What are auto-implemented properties?

    Auto-implemented properties are a shorthand way to declare properties when you don't need to add any custom logic to the `get` or `set` accessors. The compiler automatically creates the backing field.