C# Interview Question #26

What is a property in C#?

Classes, Constructors & Properties Junior Beginner

Quick Interview Answer

A property provides accessor-based access to data exposed by a class or struct. Properties normally use get, set, or init accessors.

Detailed Explanation

A property provides accessor-based access to data exposed by a class or struct. Properties normally use get, set, or init accessors.

Auto-implemented properties are concise when no custom backing logic is required. A full property can use a backing field to perform validation, transformation, logging, or other logic.

Properties are generally preferred to public fields because they preserve encapsulation and provide room for future behavior.

Code Example

private decimal _price;

public decimal Price
{
    get => _price;
    set
    {
        if (value < 0)
            throw new ArgumentOutOfRangeException(nameof(value));

        _price = value;
    }
}