Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An expression-bodied property is a syntactic shorthand in C# that utilizes the lambda arrow operator (=>) to implement property accessors as a single expression, eliminating the need for explicit block bodies ({}) and return statements. Under the hood, the compiler translates this syntax into standard block-bodied accessors. The expression on the right side of the => operator must evaluate to a type implicitly convertible to the property’s return type for a get accessor. For a set or init accessor, the expression must be a valid statement expression, which includes assignments, method invocations, object creations (new), and increment/decrement operations.

Read-Only Properties (Introduced in C# 6)

For a read-only property, the get keyword is omitted entirely. The lambda arrow operator is placed directly after the property identifier. Traditional Block Body:
public string FullName
{
    get { return $"{FirstName} {LastName}"; }
}
Expression-Bodied Equivalent:
public string FullName => $"{FirstName} {LastName}";

Read/Write and Init Properties (Introduced in C# 7 and C# 9)

For properties requiring explicit accessors, the expression-body syntax is applied individually to each accessor within the property block. Support for expression-bodied set accessors was introduced in C# 7, while support for init accessors was introduced in C# 9. Traditional Block Body:
private int _capacity;

public int Capacity
{
    get { return _capacity; }
    set { _capacity = value; }
}
Expression-Bodied Equivalent:
private int _capacity;

public int Capacity
{
    get => _capacity;
    set => _capacity = value;
}

public int InitialCapacity
{
    get => _capacity;
    init => _capacity = value;
}

Exception Throwing (Introduced in C# 7)

Expression-bodied accessors support throw expressions, allowing an accessor to immediately throw an exception without requiring a statement block.
private string _status;

public string Status
{
    get => _status;
    set => _status = value ?? throw new ArgumentNullException(nameof(value));
}

Syntax Constraints

  • The body must consist of exactly one expression.
  • It cannot contain block-level statements such as if, switch, for, or try/catch (though ternary operators ?: and switch expressions are permitted as they evaluate to a single value).
  • For set and init accessors, the compiler does not enforce state mutation. The accessor can execute any valid statement expression, such as logging a value or raising an event.
  • If a set or init accessor expression invokes a method that returns a value, the compiler simply discards the returned value, identical to the behavior within a block-bodied accessor.
Master C# with Deep Grasping Methodology!Learn More