c-sharp
  1. c-sharp-properties

C# Properties

In C#, properties provide a flexible way to encapsulate the access to private fields of a class, enabling controlled and consistent access to the data within an object. This guide covers the syntax, usage, and considerations when working with properties in C#.

Syntax

public class MyClass
{
    // Private field
    private int myField;

    // Property with get and set accessors
    public int MyProperty
    {
        get { return myField; }
        set { myField = value; }
    }
}

Example

public class Circle
{
    private double radius;

    // Property to get and set the radius
    public double Radius
    {
        get { return radius; }
        set
        {
            if (value >= 0)
                radius = value;
            else
                Console.WriteLine("Invalid radius. Setting to zero.");
        }
    }

    // Property to get the area (read-only)
    public double Area
    {
        get { return Math.PI * radius * radius; }
    }
}

class Program
{
    static void Main()
    {
        Circle myCircle = new Circle();
        
        // Set the radius using the property
        myCircle.Radius = 5.0;

        // Get the area using the property
        Console.WriteLine($"Circle Area: {myCircle.Area}");
    }
}

Output

The output will be the area of the circle calculated using the Area property.

Explanation

  • Properties provide a way to access private fields (radius in this case) in a controlled manner.
  • The Radius property has both a get and a set accessor, allowing both read and write access.
  • The Area property is read-only and calculates the area based on the radius.

Use

Use properties in C# when:

  • You want controlled access to the fields of a class.
  • You need to perform validation or additional logic when getting or setting values.
  • You want to expose read-only or write-only access to certain data.

Important Points

  • Properties can have different access modifiers (public, private, etc.).
  • Properties provide a cleaner syntax than traditional getter and setter methods.
  • Auto-implemented properties can be used when no additional logic is needed in the getter or setter.

Summary

C# properties are a fundamental aspect of object-oriented programming, providing a way to encapsulate and control access to the internal state of objects. Whether exposing or manipulating data within a class, understanding how to use properties effectively can lead to more maintainable and readable code. Consider using properties to encapsulate the state of your objects and provide controlled access to their data.

Published on: