0
0
C Sharp (C#)programming~5 mins

Expression-bodied methods in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Expression-bodied methods let you write simple methods in a shorter, cleaner way using just one line.

When a method returns a single value or expression.
When you want to make your code easier to read by reducing clutter.
When the method logic is very simple, like returning a calculation or property.
When you want to write quick helper methods without full method blocks.
Syntax
C Sharp (C#)
returnType MethodName(parameters) => expression;

The => symbol means the method returns the result of the expression directly.

No need for curly braces { } or return keyword inside the method.

Examples
This method returns the square of the input number.
C Sharp (C#)
int Square(int x) => x * x;
This method returns a greeting message using the input name.
C Sharp (C#)
string Greet(string name) => $"Hello, {name}!";
This method checks if a number is even and returns true or false.
C Sharp (C#)
bool IsEven(int number) => number % 2 == 0;
Sample Program

This program defines an expression-bodied method Double that multiplies a number by 2. It then prints the result for the number 5.

C Sharp (C#)
using System;

class Program
{
    static int Double(int n) => n * 2;

    static void Main()
    {
        int value = 5;
        Console.WriteLine($"Double of {value} is {Double(value)}");
    }
}
OutputSuccess
Important Notes

Expression-bodied methods work best for simple, single-expression methods.

For more complex logic, use regular method blocks with curly braces.

Summary

Expression-bodied methods use => to return a single expression directly.

They make simple methods shorter and easier to read.

Use them when your method only needs to return one value or expression.