3 options to return multiple values from a method in C#

There are many occasions when you might want to return multiple values for a method in C#. Below are some of the options that the developers could use to return multiple values from a method in C#.

Different Options to return multiple values from a method in C#

Option 1 : Using out keyword on parameters that will behave like return parameters.

The following method accepts id as input and returns firstname and lastname using the out keyword.

static void ReturnEmployeeName(int id, out string firstName, out string lastName)
{
    // Get the employee data by id
    firstName = "Senthil";
    lastName = "Kumar";
}

The method would be invoked as shown below.

string firstName = string.Empty,lastName = String.Empty;
ReturnEmployeeName(1,out firstName,out lastName);
Console.WriteLine(firstName + " , " + lastName);

A method in C# can have at most one return value. With the use of the our keyword , you can indicate the parameters as a kind of return value.

The out parameters need not have to be initialized. We can simply declare it and pass it in to the method. There are other options to use instead of out keyword like “ref” keyword. The out keyword is more self describing in this case stating that it is acting as a return value (out) and also that it need not be initialized before passing it to the method.

Option 2 : Return class or structure which contains all the return values.

Using the out parameter is a simple way to get things done but it can have less number of return values. When you need to return more values from a method , you can simply create a struct or class and use it as return type.

Below is a method that returns the structure of type EmployeeName.

static EmployeeName ReturnEmployeeName(int id)
{
    EmployeeName emp = new EmployeeName();
    emp.FirstName = "Senthil";
    emp.LastName = "Kumar";
    return emp;
}

The definition of the EmployeeName struct is shown below.

struct EmployeeName
{
    public string FirstName;
    public string LastName;
}

The ReturnEmployeeName method returning the struct of type EmployeeName would be something like this

EmployeeName emp = ReturnEmployeeName(1);
Console.WriteLine(emp.FirstName + " , " + emp.LastName);

Option 3 : Using Tuple

Instead of using the class or struct , you can simply return Tuple object that contains all the return values.

A tuple is immutable data type that can be used to store values of different types.

Below is a method that returns the Tuple object of the first name and Last name of the employee.

static Tuple<string, string> ReturnEmployeeNameTuple(int id)
{
    var result = Tuple.Create<string, string>("senthil", "kumar");
    return result;
}

You could invoke this method returning the Tuple as shown below

Tuple<string, string> result = ReturnEmployeeNameTuple(1);
Console.WriteLine(result.Item1 + " , " + result.Item2);

Leave a Reply