This post will discuss how to return multiple values from a method in C#.

As per C# Language Specification, returning multiple values from a method is not possible. Using some other features offered by C#, we can return multiple values to the caller method. This post provides an overview of some of the available alternatives to accomplish this.

1. Using ref parameters

We can use the ref keyword to return a value to the caller by reference. We can use it to return multiple values from a method, as demonstrated below:

Download  Run Code

 
Note that the ref keyword won’t work with the Async and Iterator methods.

2. Using out parameter modifier

The out keyword causes arguments to be passed by reference. It is like the ref keyword, except that ref requires that the variable be initialized before it is passed.

The following example demonstrates using the out parameter to return multiple values from a method.

Download  Run Code

 
Note that the out parameter won’t work with the Async and Iterator methods.

3. Using Tuple Class

A tuple is a data structure that lets you easily package multiple values in a single object. Tuples are commonly used to return multiple values from a method.

The following example creates a 2-tuple and returns it from the fun() method:

Download  Run Code

4. Using C#7 ValueTuple

Value tuples, introduced in .NET Framework 4.7, are tuple types to provide the runtime implementation of tuples in C#. Like tuple classes, We can use it to return multiple values from a method in a more effective way.

The following example uses type inference to deconstruct the 2-tuples returned by the method.

Download  Run Code

5. Using struct or Class

Here, the idea is to return an instance of a class containing all fields we want to return. The following code example returns multiple values from a method using struct.

Download  Run Code

That’s all about returning multiple values from a method in C#.