Saturday, October 4, 2014

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);
}

Regards,
Paras Wadehra
Microsoft MVP
Twitter: @ParasWadehra

1 comment:

Anonymous said...

The question is: When to use which method? What is the most understandable and clean method? I dont like tuple as it is not clear what the return value means, its only called item1, item2, etc..