You can hand values over to your Methods. The Method can then
use these values in its code. For us, we want to get two numbers from the text
boxes, and then add them up. The two values from the text boxes, then, need
to be handed over to our Method. The code to add up will go between the curly
brackets of the AddUp Method.
To hand values over to your Methods, you place them between the round brackets.
These are called parameters. (You'll also hear the term arguments, often used
to mean the same thing. There is a subtle difference, however, which you'll
see shortly. It's not crucial that you learn the difference, though!)Change your Method to this:
We can use these parameters in the code for the Method. Adapt your AddUp code so that it's like ours below:
If you try to run your code now, however, you'll get an error. There will be a wavy blue line under AddUp, along with a strange error message:
Here's the difference between an argument and a parameter: It's a parameter when you set up the values in the method; It's an argument when you're calling it (passing the values to the Method).
Change your button code to this:
Run your programme again and there shouldn't be any errors. When you click your button, you should see the answer to the addition.
Halt your programme, and change your button code to this:
You can also do this:
AddUp( number1, number2 );
The values in these two variables will get handed to our Method. But all you
are trying to do is to pass two integers over to your Method. You need two integers
because that's the way you set the Method up.One more thing to note, here. When we set the Method up, the two parameters were called firstNumber and secondNumber. When we called it from the button, however, the two variables are called number1 and number2. So we've used different variables names. This is perfectly OK, and C# doesn't get confused. All that matters is that you are passing the correct information over to the Method.
You will also want to get values back from your Methods, and you'll see how to do that in the next lesson.
0 comments:
Post a Comment