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.00
Tax (10%): 100.00
Total Price: 1100.00
Discount (15%): 150.00
Final Price: 950.00Format every monetary value to exactly two decimal places — for example value.ToString("F2") or $"{value:F2}". That applies to the base price, the tax, the total, the discount and the final price alike.
Remember to use the => arrow syntax for all members that contain a single expression. This keeps your code clean and readable!
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());
// Create a Product object using the input values
Product product = new Product(name, basePrice);
// Calculate the discount amount using GetDiscount method
decimal discountAmount = product.GetDiscount(discountPercentage);
// Calculate the final price using GetFinalPrice method
decimal finalPrice = product.GetFinalPrice(discountPercentage);
// Print the pricing details in the required format:
Console.WriteLine($"Product: {product.Name}");
Console.WriteLine($"Base Price: {product.BasePrice:F2}");
Console.WriteLine($"Tax (10%): {product.TaxAmount:F2}");
Console.WriteLine($"Total Price: {product.TotalPrice:F2}");
Console.WriteLine($"Discount ({discountPercentage}%): {discountAmount:F2}");
Console.WriteLine($"Final Price: {finalPrice:F2}");
}
}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