Typically, you can only return one thing in C#. For instance, you may return an
string or an array of
bools. As you may have surmised, output parameters allow you to return multiple values without using a container.
Let's take a look at a simple method:
x and storing the answer in our
result variable. We've added the
out modifier to our
result varible to signify it is an output parameter. Let's see what this means:
Passing in 10 and 4 as the first two arguments to
Subtract should not throw you off. You may be wondering about our little friend
result. What's happening here is that in
Subtract, we're assigning a value to
result. When we call
Console.WriteLine, we can pass in
result as the third argument and we get our expected result:
This is the output you get if you run this:
One thing to note before we move in is that we had to specify the
out modifier in the parameter list of
Subtract (figure 1) and in the argument list when calling
Subtract (figure 2). I didn't initialise
result before invoking
Subtract, but this requires C# 7 or later.
Some of you may be wondering what would happen if we hadn't assigned
Subtract. Would we get a compiler error in
Console.WriteLine() since we hadn't assigned a value or would the compiler complain about us not setting a value for
result in Subtract? It's the latter: the compiler requires us to assign a value in
Subtract. You have to assign a value to it before using it.
Great, but why on earth would you want to do that? You wouldn't, this is just a toy example, but that's not to say that output parameters aren't useful – they can be. They can be useful in places where you may want to return multiple things.
Example II: returning multiple output parameters
Let's now take a look at a method that returns multiple output parameters:
In this example, all three parameters are output parameters. That means that all three will be returned.
And the output:
As you can see from figure 5, the name I gave to the
firstName) did not need to match the name of the parameter in
name). The same goes for any of the other parameters: I could have given
isHungry different names to the names of the parameters in
Figure 5 also shows you that the
out variables can already have been assigned to values.
With an array, all of the items in it have to be of the same type. Here, we have seen how to return multiple values from a method. There are other ways to do this (e.g. using an object), but you may find this to be useful for your specific use case.
Note that tuples (the
ValueTuple data type) is a container that can store values of different data types. However, it would be wrong to necessarily think of tuples as an alternative to output parameter (although you may be able to use a tuple in place of output parameters). As since a tuple itself can be an ouput parameters. As such, should you want to, you could have multiple tuple output parameters.