Properties in C#

Properties in C# provide a clean way to access and control the data stored inside an object. They look like fields when used from outside the class, but internally they can contain logic through get and set accessors. This makes properties one of the most used features in C# classes.

In object oriented programming, a class should protect its internal state. If every field is public, outside code can assign invalid values directly. Properties solve this problem by giving controlled access to data while keeping the syntax simple for the caller.

C# properties are used in models, DTOs, configuration classes, Entity Framework entities, ASP.NET Core APIs, desktop applications, game objects, and almost every real C# project. Understanding properties properly is important before moving deeper into encapsulation, inheritance, interfaces, and modern C# design.


What Are Properties in C#?

A property is a class member that provides a flexible mechanism to read, write, or compute the value of a private field. A property usually has a get accessor, a set accessor, or both.

class Student
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

Here, Name is a property and name is a private field. Outside code can use the property like a field, but the class still controls what happens during read and write operations.

Student student = new Student();
student.Name = "Aarav";
Console.WriteLine(student.Name);

The caller does not call get or set directly. C# automatically calls the correct accessor depending on whether the property is being read or assigned.

Property Syntax in C#

accessModifier dataType PropertyName
{
    get
    {
        return valueToReturn;
    }
    set
    {
        field = value;
    }
}

Inside the set accessor, C# provides a special keyword named value. It represents the value being assigned to the property.

Fields vs Properties in C#

A field stores data directly inside a class. A property controls access to data. This difference is important because a public field gives outside code full control, while a property allows the class to add validation, computed logic, private setters, or future behavior without changing the public syntax.

PointFieldProperty
PurposeStores data directlyControls access to data
ValidationNo built-in control when publicCan validate inside setter
EncapsulationWeak if publicStrong when designed properly
Syntax for callerObject.FieldObject.Property
Best practiceKeep privateExpose public when needed

In most C# classes, fields are kept private and properties are exposed publicly. This keeps object state protected while still allowing other code to use the object naturally.

Auto-Implemented Properties

An auto-implemented property is a short property syntax where C# automatically creates the hidden backing field. Use it when no custom logic is required in the getter or setter.

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

This is very common in model classes and DTOs. The compiler creates the backing fields internally, so you do not need to write private fields manually.

Read-Only Properties

A read-only property has a get accessor but no public set accessor. This means outside code can read the value but cannot change it directly.

class Circle
{
    public double Radius { get; }

    public Circle(double radius)
    {
        Radius = radius;
    }
}

The Radius property is assigned in the constructor and then remains fixed for that object. This is useful when a value should be provided during object creation and protected after that.

Private Setters in C#

A property can have a public getter and a private setter. This allows outside code to read the value, but only the class itself can change it.

class Order
{
    public decimal TotalAmount { get; private set; }

    public void AddItem(decimal price)
    {
        if (price > 0)
        {
            TotalAmount += price;
        }
    }
}

Outside code cannot directly assign TotalAmount. It must call AddItem, which lets the class protect its own rules. This pattern is very useful in business logic.

Properties with Validation

Properties can protect an object from invalid values. Instead of allowing outside code to assign anything, the setter can check the value and accept only valid data.

class Student
{
    private int age;

    public int Age
    {
        get { return age; }
        set
        {
            if (value >= 0 && value <= 120)
            {
                age = value;
            }
            else
            {
                throw new ArgumentException("Age must be between 0 and 120");
            }
        }
    }
}

This keeps invalid age values away from the object. A property setter is a good place for simple validation, especially when the rule belongs directly to that value.

Computed Properties in C#

A computed property does not store its own value. Instead, it calculates the value from other data whenever the property is read.

class Rectangle
{
    public double Length { get; set; }
    public double Width { get; set; }

    public double Area
    {
        get { return Length * Width; }
    }
}

The Area property is calculated from Length and Width. There is no separate area field. This avoids duplicate data and keeps the value always updated.

Expression-Bodied Properties

For simple computed properties, C# supports expression-bodied syntax. It keeps small properties readable and removes unnecessary braces.

class Rectangle
{
    public double Length { get; set; }
    public double Width { get; set; }

    public double Area => Length * Width;
}

This version works the same as a get-only computed property. Use expression-bodied properties when the expression is short and obvious.

init-Only Properties in C#

An init accessor allows a property to be assigned during object initialization but not changed later. This is useful for immutable-style objects where values should be set once.

class UserProfile
{
    public string Username { get; init; }
    public string Email { get; init; }
}

UserProfile profile = new UserProfile
{
    Username = "coder",
    Email = "coder@example.com"
};

After initialization, Username and Email cannot be assigned again. This feature is useful in modern C# when designing objects that should not change after creation.

Static Properties in C#

A static property belongs to the class itself, not to one object. It is accessed using the class name. Static properties are useful for shared configuration, counters, application state, or values that logically belong to the type.

class AppInfo
{
    public static string ApplicationName { get; set; } = "NerdsDoStuff";
}

Console.WriteLine(AppInfo.ApplicationName);

Use static properties carefully. Shared mutable state can make large programs harder to test and debug. If a value belongs to each object separately, use an instance property instead.

Properties and Encapsulation

Properties support encapsulation because they allow a class to hide its internal storage while exposing safe access. Outside code should not need to know whether the value comes from a field, a calculation, a database, or another object. It only needs to use the property.

This flexibility is useful during maintenance. A simple auto-property can later be changed into a full property with validation without changing the public calling syntax. That is one reason public properties are preferred over public fields in C#.

Common Mistakes with Properties

  • Using public fields instead of properties in normal class design.
  • Adding heavy logic inside property getters.
  • Throwing unexpected exceptions from simple property reads.
  • Using public setters for values that should be controlled by methods.
  • Creating computed properties that do expensive calculations repeatedly.
  • Confusing read-only properties with private setters.

A property should feel lightweight to the caller. If a property performs a slow database query or a long calculation every time it is read, a method name may communicate the cost more clearly.

Best Practices for Properties in C#

  • Use properties instead of public fields for public data access.
  • Keep backing fields private.
  • Use auto-properties when no custom logic is needed.
  • Use private setters when only the class should modify the value.
  • Use validation in setters when the rule belongs to the property.
  • Use computed properties for values derived from other data.
  • Use init for values that should be assigned only during initialization.

Properties in Real Application Design

In real applications, properties often represent the public data contract of a class. For example, an API response object may expose properties such as Id, Name, Email, and CreatedAt. A domain object may expose read-only values publicly but change them only through methods that enforce business rules.

This design keeps the class honest. A bank account should not let outside code set the balance to any random number. It should expose a balance property for reading, then provide deposit and withdraw methods that validate each operation. Properties and methods should work together to protect object state.

Properties Interview Points

For interviews, remember that properties are not the same as fields. A property is a member with accessors. The get accessor reads a value, and the set accessor assigns a value using the special value keyword. Auto-properties are shorthand properties where the compiler creates the backing field.

Also remember the difference between get-only, private set, and init-only properties. A get-only auto-property can usually be assigned in a constructor. A private setter can be changed inside the class. An init-only property can be assigned during object initialization and then becomes fixed.

Good property design makes classes easier to use, safer to modify, and clearer during debugging because each value has an obvious owner and a controlled update path.

FAQs on Properties in C#

Why use properties instead of public fields?

Properties allow validation, computed values, private setters, and future logic while keeping simple field-like syntax for the caller. Public fields expose data too directly.

What is an auto-property in C#?

An auto-property is a property where the compiler automatically creates the hidden backing field. Example: public string Name { get; set; }.

Can a property be read-only?

Yes. A property can have only a getter, or it can have a public getter with a private setter. Both designs restrict outside modification.

Can properties contain logic?

Yes, properties can contain logic in getters and setters. Keep that logic simple and predictable. Expensive operations are usually better represented as methods.