Expression-Bodied Members
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 14 of 70.
Expression-bodied members provide a concise syntax for members that contain only a single expression. Instead of writing full method or property bodies with braces, you use the => arrow syntax.
For methods that return a single expression, you can replace the entire body:
// Traditional method
public int Add(int a, int b)
{
return a + b;
}
// Expression-bodied method
public int Add(int a, int b) => a + b;This syntax works for read-only properties too, which you've already seen briefly:
public class Circle
{
public double Radius { get; set; }
public double Area => Math.PI * Radius * Radius;
public double Circumference => 2 * Math.PI * Radius;
}You can also use expression bodies for property getters and setters individually:
private string name;
public string Name
{
get => name;
set => name = value.Trim();
}Even constructors can use this syntax when they contain a single statement:
public class Person
{
public string Name { get; }
public Person(string name) => Name = name;
}Expression-bodied members make your code more readable when the logic is simple. Use them for straightforward operations, but stick with traditional bodies when you need multiple statements or complex logic.
Challenge
EasyLet's build a product pricing calculator that showcases the power of expression-bodied members to write clean, concise code.
You'll create two files to organize your code:
Product.cs: Define aProductclass in theStorenamespace. This class should demonstrate various expression-bodied members:- An auto-implemented property
Name(string) andBasePrice(decimal) - An expression-bodied constructor that sets both properties
- An expression-bodied read-only property
TaxAmountthat calculates 10% of the base price - An expression-bodied read-only property
TotalPricethat returns the base price plus tax amount - An expression-bodied method
GetDiscount(decimal percentage)that returns the discount amount (base price multiplied by percentage divided by 100) - An expression-bodied method
GetFinalPrice(decimal discountPercentage)that returns the total price minus the discount
- An auto-implemented property
Program.cs: In your main file, create aProductusing input values, then display its pricing breakdown.
You will receive three inputs:
- Product name
- Base price
- Discount percentage to apply
Print the pricing details in this format:
Product: {Name}
Base Price: {BasePrice}
Tax (10%): {TaxAmount}
Total Price: {TotalPrice}
Discount ({percentage}%): {discountAmount}
Final Price: {finalPrice}For example, if the inputs are Laptop, 1000, and 15, the output should be:
Product: Laptop
Base Price: 1000
Tax (10%): 100
Total Price: 1100
Discount (15%): 150
Final Price: 950Remember to use the => arrow syntax for all members that contain a single expression. This keeps your code clean and readable!
Cheat sheet
Expression-bodied members use the => arrow syntax for members containing a single expression, providing a concise alternative to traditional method and property bodies.
Expression-bodied methods:
// Traditional method
public int Add(int a, int b)
{
return a + b;
}
// Expression-bodied method
public int Add(int a, int b) => a + b;Expression-bodied read-only properties:
public class Circle
{
public double Radius { get; set; }
public double Area => Math.PI * Radius * Radius;
public double Circumference => 2 * Math.PI * Radius;
}Expression-bodied property getters and setters:
private string name;
public string Name
{
get => name;
set => name = value.Trim();
}Expression-bodied constructors:
public class Person
{
public string Name { get; }
public Person(string name) => Name = name;
}Use expression-bodied members for straightforward operations. For multiple statements or complex logic, use traditional bodies.
Try it yourself
using System;
using Store;
class Program
{
public static void Main(string[] args)
{
// Read inputs
string name = Console.ReadLine();
decimal basePrice = Convert.ToDecimal(Console.ReadLine());
decimal discountPercentage = Convert.ToDecimal(Console.ReadLine());
// TODO: Create a Product object using the input values
// TODO: Calculate the discount amount using GetDiscount method
// TODO: Calculate the final price using GetFinalPrice method
// TODO: Print the pricing details in the required format:
// Product: {Name}
// Base Price: {BasePrice}
// Tax (10%): {TaxAmount}
// Total Price: {TotalPrice}
// Discount ({percentage}%): {discountAmount}
// Final Price: {finalPrice}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator