CHASH Tutorial



C# PROPERTIES


C# Properties

Properties in C# provide a flexible mechanism to read, write or compute the values of private fields. They are special methods called accessors that control access to class data.

Why Use Properties?

  • Encapsulate private fields.
  • Provide controlled access (get and/or set).
  • Allow validation when setting values.
  • Maintain backward compatibility if internal implementation changes.

Basic Property Syntax

class Person
{
    private string name;  // private field

    // Property for name with get and set accessors
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}
  

Auto-Implemented Properties

If no extra logic is needed, you can use auto-properties which let the compiler create the hidden backing field automatically:

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

Read-Only and Write-Only Properties

  • Read-Only: Property has only a get accessor.
  • Write-Only: Property has only a set accessor (rarely used).

Example: Read-Only Property

class Person
{
    public string Name { get; }  // read-only

    public Person(string name)
    {
        Name = name;  // can set only inside constructor
    }
}
  

Example: Property with Validation

class Person
{
    private int age;

    public int Age
    {
        get { return age; }
        set
        {
            if (value >= 0)  // validate age
                age = value;
            else
                throw new ArgumentException("Age cannot be negative");
        }
    }
}
  

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review