Share via


Returning multiple values from a method

During your programming escapades you are sure to come across an instance when you need to return multiple values from a method.

 

The traditional ways of doing it are:

(i) to create an object of a class, instantiate it and assign values to the object inside the method and then return the object from the method, or

(ii) to assign values to multiple global variables inside the method and then access them elsewhere, or

(iii) to use an out parameter to return the updated value back to the calling method, or

(iv) to use a ref parameter to modify the referenced parameter directly from inside the called method.

Well, there is another lesser-known way in .Net that allows you to return multiple values from a method without having to create an object or multiple variables, it is a feature called Tuple.

Here is some sample code in C# that shows you how to create and use a Tuple to return multiple values from a method:

public Tuple<int, string, string> GetEmployee()
{

    int employeeId = 23;

    string firstName = "John";

    string lastName = "Doe";

//Create a tuple and return

    return Tuple.Create(employeeId, firstName, lastName);
}

Via Blogger

Regards,
Paras Wadehra
Microsoft MVP
Twitter: @ParasWadehra
FB.com/MSFTDev
My Mobile Apps

Comments

  • Anonymous
    October 05, 2014
    I agree. Tuples are very convenient. That's the way I do it.

  • Anonymous
    October 07, 2014
    Imho, when ever you try to return multiple values your method does too much. So in your example if you want to get an employee  return an employee. I know its just a simple showcase, but my rule does apply to broader usecases aswell.