.NET Tips and Tricks

Blog archive

Return Multiple Values from Methods with Tuples

You have a method that returns multiple values. So you have to define a class, instantiate it, set the properties to the values, and return the resulting object, right? Well, no you don't -- at least in .NET Framework 4, which gives you a simpler way: Tuples.

A Tuple can hold up to eight values (including classes) and can be created on the fly. To declare and instantiate a Tuple that could hold two values (one string and one integer), you'd use code like this:

  Dim tup As New Tuple(Of Integer, String)

When you instantiate a new tuple, you also pass the values that will be put in the Tuple. So instantiating the Tuple and putting the number 2 and the string "fred" in it would require this code:

  Dim tup As New Tuple(Of Integer, String)
              (2, "fred")

There's no need to define a special purpose class to return some arbitrary collection of values.

Here's a more useful example: A method that returns a List of Customer objects. However, the method also returns an error code and a human-readable error message. Rather than defining a class, the code just declares a Tuple with an integer, a string, and List of Customers:

  Function ReturnData(Region As String) _
As Tuple(Of Integer, String, List(Of Customer))

Dim cust As Customer Dim lst As New List(Of Customer) Dim errorCode As Integer Dim errorMessage As String

'code to add customers to lst and catch errors

Dim tup As New Tuple(Of Integer, String, List(Of Customer)) (errorCode, errorMessage, lst) Return tup

End Function

The code that calls this method would use Item* properties on the Tuple to access the values. A Tuple, like this one, with three items stored in it will have properties called Item1, Item2, and Item3 (and all the properties will have the right data type).

To call the method, check for an error, and either display the error message or process the Customers in the list if everything works right, you'd write code like this:

  Dim retData As Tuple(Of Integer, String, List(Of Customer))
  
  retData = ReturnData("NA")
  
 If retData.Item2 < 0 Then
     MessageBox.Show(retData.Item2)
  Else
     For Each cust In retData.Item3
       'process Customers
     Next        
  End If

Editor's Note: This article has been updated to reflect that Tuples can hold up to eight values, not four.

Posted by Peter Vogel on 12/08/2011 at 1:16 PM


comments powered by Disqus
Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.