Return multiple values from a method

This falls under the category of “I would have known about this if I was not self-taught, and it would have saved me so much time.”

In general, the methods I have written in the past have only been able to cope with a single return value. This is not a problem if you want, for example, to return a value from a DataSet, or a simple transform. However, there are occasions where you need to do multiple operations on a single set of data. An example might be statistical analysis on a set of integers – return the average, the sum, minimum and maximum values, etc.

I discovered the out keyword today, and it used as follows.

private void GetStatistics(int value1, int value2, out int sum, out int difference) { sum = value1 + value2; if(value1 > value2) difference = value1 - value2; else difference = value2 - value1; } private void process_Click(object sender, System.EventArgs e) { int sum; int diff; GetStatistics(34,82,out sum,out diff); label1.Text = "Sum :: " + sum.ToString(); label2.Text = "Difference :: " + diff.ToString(); }

The out keyword specifies that the parameter is to be returned when the function completes. In this simple example, the result would be that label1 shows “Sum :: 116″, and label2 shows “Difference :: 48″. It is that easy.

You will notice that in this example, there is no return value (since it is a void function), but it can be amended to allow different method types.

private string GetStatistics(int value1, int value2, out int sum, out int difference) { sum = value1 + value2; if(value1 > value2) difference = value1 - value2; else difference = value2 - value1; return "I have finished that for you, sir"; } private void button1_Click(object sender, System.EventArgs e) { int sum; int diff; MessageBox.Show(GetStatistics(34,82,out sum,out diff)); label1.Text = "Sum :: " + sum.ToString(); label2.Text = "Difference :: " + diff.ToString(); }

In this example, you can see that the out parameters do not have to even be the same type as the method. Here we return a string from the method, alongside the sum and difference integer values.

Powerful, I think.