> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# C# Expression-Bodied Method

An expression-bodied method is a syntactic shorthand in C# that allows a method's implementation to be defined using a single expression instead of a standard statement block. It utilizes the expression body definition operator (`=>`) to map the method signature directly to its evaluating expression, eliminating the need for curly braces (`{}`) and explicit `return` statements.

At the Intermediate Language (IL) level, the C# compiler translates an expression-bodied method exactly as it would a traditional block-bodied method. It is strictly a compile-time syntactic sugar.

## Syntax

```csharp theme={"dark"}
[modifiers] [return_type] MethodName([parameters]) => expression;
```

## Mechanics and Evaluation Rules

The behavior and compilation of an expression-bodied method depend on its signature:

**1. Non-Void Return Types**
If the method declares a return type other than `void`, the `expression` to the right of the `=>` operator must evaluate to a value that is implicitly convertible to the declared return type. The compiler automatically generates the underlying `return` statement.

*Async Methods:* For `async` methods, the expression must be implicitly convertible to the method's *result type*, not its declared return type. For example, if the declared return type is `Task<string>`, the `await` expression must evaluate to `string`. The compiler automatically handles the state machine generation and `Task` wrapping.

**2. Void Return Types**
If the method declares a `void` return type, the `expression` must be a valid *statement expression*. In C#, statement expressions are restricted to method invocations, object creation (`new`), assignments, increment/decrement operations, and `await` expressions.

**3. Throw Expressions**
A `throw` expression implicitly converts to any type. Therefore, it is a valid expression body for both `void` methods and non-void methods.

## Executable Example

The following complete program demonstrates expression-bodied methods across various return types, modifiers, and expression categories.

```csharp theme={"dark"}
using System;
using System.Net.Http;
using System.Threading.Tasks;

public class ExpressionBodiedExamples
{
    // Required fields for the examples
    private int _internalCounter = 0;
    private static readonly HttpClient httpClient = new HttpClient();
    private readonly string url = "https://example.com";

    // 1. Non-Void Return Type
    // Evaluates to int, matching the declared return type.
    public int Multiply(int a, int b) => a * b;

    // 2. Void Return Type (Statement Expression)
    // Console.WriteLine is a method invocation.
    public void LogError(string message) => Console.WriteLine(message);

    // 3. Async Expression-Bodied Method (Await Expression)
    // The await expression evaluates to 'string', matching the result type of Task<string>.
    public async Task<string> FetchDataAsync() => await httpClient.GetStringAsync(url);

    // 4. Ref Return Expression-Bodied Method
    public ref int GetReference() => ref _internalCounter;

    // 5. Tuple Return Expression-Bodied Method
    public (int X, int Y) GetCoordinates() => (10, 20);

    // 6. Throw Expressions
    // Valid for both void and non-void return types.
    public void DoWork() => throw new NotImplementedException();
    public int GetValue() => throw new InvalidOperationException();
}

public class Program
{
    public static async Task Main()
    {
        var example = new ExpressionBodiedExamples();
        
        // Testing Non-Void
        Console.WriteLine($"Product: {example.Multiply(5, 4)}");
        
        // Testing Void
        example.LogError("Execution started.");
        
        // Testing Async
        try
        {
            string data = await example.FetchDataAsync();
            Console.WriteLine($"Fetched {data.Length} bytes.");
        }
        catch (HttpRequestException ex)
        {
            example.LogError($"Network error: {ex.Message}");
        }
        
        // Testing Ref Return
        ref int counterRef = ref example.GetReference();
        counterRef = 42; // Mutates _internalCounter directly
        
        // Testing Tuple Return
        var coords = example.GetCoordinates();
        Console.WriteLine($"Coordinates: X={coords.X}, Y={coords.Y}");
    }
}
```

## Structural Limitations

Because the right side of the `=>` operator must be a single evaluable expression, expression-bodied methods cannot contain:

* Block-level control flow statements (`if`, `while`, `for`, `foreach`). *Note: `switch` expressions and ternary operators (`?:`) are permitted because they evaluate to a value.*
* `try-catch-finally` blocks.
* Multiple distinct statements separated by semicolons.
* Standalone local variable declaration statements (e.g., `int x = 5;`). *Note: Inline local variable declarations via `out` variables (e.g., `int.TryParse(input, out int result)`) and pattern matching (e.g., `obj is string s`) are fully supported as they are part of a single expression.*

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor C# Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
