Expression-Bodied Members
Expression-bodied members are one-line ways to write short methods and properties, like a quick answer instead of a full essay. They use an arrow to give the result.
In this page:
Syntax
public ReturnType MethodName() => expression;
public type PropertyName => expression;
public ClassName(type parameter) => field = parameter;
Expression-Bodied Members
Expression-bodied members let you write a method, property, or constructor whose entire body is a single expression using => instead of a full { } block with a return.
This is purely a syntactic shortcut for one-line members and doesn't change behavior. It's widely used for simple properties and small computed methods.
Note:
Expression-bodied syntax works for methods, read-only properties, and even constructors and finalizers — not just fields.
Example: Expression-Bodied Members
using System;
class Circle
{
public double Radius;
public Circle(double radius) => Radius = radius;
public double Area => Math.PI * Radius * Radius;
public double Diameter() => Radius * 2;
}
class Program
{
static void Main(string[] args)
{
Circle c = new Circle(4);
Console.WriteLine(c.Area);
Console.WriteLine(c.Diameter());
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Confusing
public double Area => Math.PI * Radius * Radius;with{ get; } = ...; the=>version recalculates on every access instead of storing a value once. - Trying to put several statements after
=>, when an expression-bodied member allows only a single expression; use a normal{ }body. - Expecting an expression-bodied property to have a setter, when
=>on a property creates a read-only getter.
Chapter Summary
- Records define immutable data types, and tuples and deconstruction group and unpack values.
- Pattern matching checks values and shapes concisely.
- Nullable reference types and expression-bodied members make code safer and shorter.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: