anonymous method
return value
programming
C#
lambda expressions

How to return value with anonymous method?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In C#, an anonymous method is an inline delegate body assigned to a delegate type. It can return a value as long as the delegate type expects one, which is why the real question is usually not "can it return," but "what delegate signature am I returning through?"

Return through a delegate that has a non-void result

Anonymous methods are tied to delegate types. If the target type returns int, bool, string, or any other value, the anonymous method can use return exactly like a normal method.

csharp
1using System;
2
3class Program
4{
5    static void Main()
6    {
7        Func<int, int, int> add = delegate(int left, int right)
8        {
9            return left + right;
10        };
11
12        Predicate<string> isShort = delegate(string text)
13        {
14            return text.Length < 5;
15        };
16
17        Console.WriteLine(add(2, 3));
18        Console.WriteLine(isShort("code"));
19    }
20}

The key point is that Func<int, int, int> expects an int result and Predicate<string> expects a bool result. The anonymous method must satisfy that contract.

Pick the right delegate type first

If you assign an anonymous method to Action, it cannot return a value because Action represents void. If you need a value back, use Func or a custom delegate.

csharp
1using System;
2
3delegate decimal DiscountCalculator(decimal price);
4
5class Program
6{
7    static void Main()
8    {
9        DiscountCalculator calculator = delegate(decimal price)
10        {
11            return price * 0.9m;
12        };
13
14        Console.WriteLine(calculator(100m));
15    }
16}

A custom delegate is useful when the signature has business meaning. DiscountCalculator tells a reader more than Func<decimal, decimal> when the codebase has several similar callbacks.

return exits the anonymous method, not the outer method

One common misunderstanding is expecting return inside the anonymous method to return from the containing method. It does not. It returns only from the delegate body.

csharp
1using System;
2
3class Program
4{
5    static void Main()
6    {
7        Console.WriteLine(Compute());
8    }
9
10    static int Compute()
11    {
12        Func<int> getValue = delegate
13        {
14            return 10;
15        };
16
17        int value = getValue();
18        return value + 5;
19    }
20}

Compute returns 15, not 10, because the first return completes only the delegate invocation.

Anonymous methods can capture outer variables

Like lambda expressions, anonymous methods can close over variables from the surrounding scope. That is often useful when the returned value depends on configuration or state that already exists.

csharp
1using System;
2
3class Program
4{
5    static void Main()
6    {
7        int taxRate = 13;
8
9        Func<decimal, decimal> addTax = delegate(decimal subtotal)
10        {
11            return subtotal + subtotal * taxRate / 100m;
12        };
13
14        Console.WriteLine(addTax(50m));
15    }
16}

This is convenient, but it also means the returned result depends on captured state. If that state changes later, the delegate result may change too. That can surprise people reading event-driven or asynchronous code.

Anonymous methods and lambdas solve the same problem

Modern C# code often uses lambdas instead of the older delegate syntax because lambdas are shorter. The runtime idea is the same. If you understand how an anonymous method returns a value, you already understand the lambda version.

csharp
1Func<int, int> square1 = delegate(int x)
2{
3    return x * x;
4};
5
6Func<int, int> square2 = x => x * x;

For new code, lambdas are usually the better default. Anonymous methods still appear in older codebases, generated examples, and interview discussions, so it is worth knowing how the return behavior maps.

Common Pitfalls

  • Assigning the anonymous method to Action and then wondering why return someValue; does not compile.
  • Expecting return inside the anonymous method to exit the outer method.
  • Forgetting that all code paths in a non-void anonymous method must return a value.
  • Capturing mutable outer variables and then getting different results later than expected.
  • Using anonymous methods where a short lambda would make the intent easier to read.

Summary

  • Anonymous methods can return values when the delegate type expects a non-void result.
  • Use Func or a custom delegate when you need a returned value.
  • 'return exits the anonymous method body, not the containing method.'
  • Captured outer variables can affect the returned result.
  • Lambdas are a shorter syntax for the same delegate-based idea.

Course illustration
Course illustration

All Rights Reserved.