What is Expression Body in C# and How to Use It
expression body is a concise way to write methods, properties, or other members using a single expression instead of a full block of code. It uses the => symbol followed by an expression, making code shorter and easier to read.How It Works
Think of an expression body like a shortcut for writing simple code. Instead of writing multiple lines with curly braces and a return statement, you write just one line that directly shows what the method or property returns or does.
Imagine you want to tell a friend how to get to your house. Instead of giving a long explanation, you just say, "Turn left at the store." Expression bodies work the same way by giving a quick, clear instruction in one line.
In C#, this is done by using the => symbol followed by the expression. This replaces the usual block of code inside curly braces, making your code cleaner and easier to understand at a glance.
Example
This example shows a method and a property using expression bodies to return values simply and clearly.
using System; class Program { // Method with expression body static int Square(int x) => x * x; // Property with expression body public string Name => "Alice"; static void Main() { Console.WriteLine(Square(5)); // Output: 25 Program p = new Program(); Console.WriteLine(p.Name); // Output: Alice } }
When to Use
Use expression bodies when your method or property is simple and can be written in one clear expression. This makes your code shorter and easier to read, especially for small calculations or returning values.
For example, use expression bodies for simple getters, small helper methods, or any place where a full block of code feels too long for what you want to do.
However, if your code needs multiple steps or more complex logic, stick to the regular block syntax with curly braces to keep it clear.
Key Points
- Expression bodies use
=>followed by a single expression instead of curly braces. - They make simple methods and properties shorter and easier to read.
- Best for simple return statements or single expressions.
- Not suitable for complex logic requiring multiple statements.