Skip to main content
Published on

Properties in C#

Share:

Introduction

In C#, as in many object-oriented programming languages, encapsulation is a fundamental practice. It promotes the protection and integrity of data by restricting direct access to it. Properties play a crucial role in this regard.

What are Properties?

A property is a member of a class that provides a mechanism for getting or setting the value of an internal field. Instead of accessing the field directly, you can use properties to interact with it, ensuring that any logic associated with reading or writing the field is respected.

Benefits of Properties

  1. Encapsulation: Properties help protect data, preventing it from being modified in an unwanted way.
  2. Validation: Before assigning a value, you can ensure it is within a certain range or satisfies other conditions.
  3. Computed Representation: Properties can return a calculated value instead of a stored value.

Deep Dive into get and set

  • get: This accessor is used when the property value is read. Additional logic, such as calculations or transformations, can be added before returning the value.
  • set: This accessor comes into action when you try to modify the property value. This is where validation or other logic related to modifying the value occurs.

Read-Only and Write-Only Properties

  • Read-Only: A property that only defines the get accessor.
  • Write-Only: Although rare, these are properties that only define the set accessor.

Advanced Examples

Beyond the basic example, let's explore a bit more:

public class Circle {
  private double radius;

  public double Radius {
    get { return radius; }
    set {
      if (value < 0)
        radius = 0;
      else
        radius = value;
    }
  }

  // Read-only property
  public double Area {
    get {
      return Math.PI * radius * radius;
    }
  }
}

In this example, we have a Circle class that has a Radius property and a read-only Area property. The Radius cannot be negative, and the Area is calculated based on the Radius.

Conclusion

The correct use of properties in C# is essential to ensure that data is handled in a safe and controlled manner. They offer a structured way to interact with the fields of a class, maintaining data integrity and offering flexibility in implementation.

Happy coding!