This lesson will cover the out keyword that is used alongside ordinary input parameters in order to output a value other than the return value. We already saw it used in a previous lesson that called the double.TryParse() method where we witness how the output parameter sent a value back out of the method, similar to the way a return value works but with a twist.
You should create a project for this lesson based on where we left off with the previous lesson, and call it “CS-ASP_034”. In the previous lesson we had a method called performAttack() that held most of the battle code. In this lesson, we will want to replace it with a new method called defeatEnemy() that functions a bit differently. Here we see that the method still performs the main battle algorithm, but it also returns a bool depending on whether or not the enemy has zero or less remaining health:
Suppose that you want the defeatEnemy() method to also return the defender’s health. Since we’re only allowed a single method return value, the best way around this is to have the defender’s health value come back out as an out parameter:
Now you can reference this method within a conditional statement and perform some sort of action depending on the returned value:
And now create the lootEnemy() method, which simply displays a message through resultLabel.Text:
It may not be clear why the out keyword is needed here. The way that input parameters normally work is that local variables provided as input at method calls have their values copied into the local input parameter and so there is no reference retained back to the original variable where the value was copied from. Whatever information is processed in the method is local to the method itself, unless it comes back out as a returned value, or an output parameter.
You can almost think of methods as being their own little “universe” that may hold copies of variables from another “universe,” supplied via input parameters. And the only way that a method can “talk back” to the world it copied information from is via the return, out and ref keywords, or else if there is a class-level variable referenced in the method. Otherwise, a method’s internals are completely sealed off from its surroundings. Also, note that although the out keyword can solve a variety of problems, it is not very common, and should be used sparingly considering that it can be seen as violating the principle of “Single Responsibility.”
Lesson 34 - Creating Methods with Output Parameters