Blogger templates

Pages

Tuesday 22 October 2013

Understanding C# Methods

So far, all of your programming code has gone between the curly brackets of buttons. But this is not an effective way to programme. If you keep all your code in one place, it will become more and more unreadable the longer it gets. Instead, you can use something called a Method.
A Method is just a segment of code that does a particular job. Think about the calculator programme you have been working on. You can have one Method ( a chunk of code) to add up, one to subtract, another one to divide, and a fourth Method to multiply. The idea is that when you want to add up, you just call the Add Up Method into action.
To get you started with Methods, we'll create a simple programme that takes two numbers from text boxes. We'll have four buttons, one to add up, one to subtract, one to divide, and one to multiply. We'll use Methods to do the calculating. Off we go then!
Create a new C# project, and design the following form:
Design this C# form
You can keep the buttons and text boxes on their default names (button1, button2, textbox1, textbox2, etc.)
Double click the Add Up button to open up the coding window. The cursor will be flashing inside of the button code. However, you create Methods outside of any other code. So move the cursor after the final curly bracket of the button code. Then hit your enter key a few times to give yourself some space. Type the following:
void AddUp()
{
MessageBox.Show("Add Up Here");
return;
}
Your coding window will then look like ours below:
The Method is added outside of the button code
Methods can return a value, such as the answer to the addition. But they don't have to. Our Method above just displays a message box when it is called into action. If you don't want anything back from your Methods, you set them up by typing the keyword void. After a space, you need to come up with a name for your Method. We've called ours AddUp. But they are just the same as variable names, and you call them almost anything you like. (The same rules apply to naming Methods as they do to naming Variables.)
After coming up with a name for your Method, you type a pair of round brackets. You can put things between the round brackets, and you'll see how to do that shortly.
After the round brackets, you need a pair of curly brackets. The code for your Method goes between the curly brackets. For us, this was just a Message Box.
Before the final curly bracket, we've typed the word return, followed by a semicolon. This is not necessary, if you've set your Method up as void, since you don't want it to return anything: you just want it to get on with its job. We've added the return keyword because it's just standard practice. But when C# sees the return keyword, it will break out of your Method. If you type any code after that, it won't get executed. (You'll see a different way to use the return keyword when we want to get something back from a Method.)


Calling your Methods

Our Method is not doing much good at the moment, since it's not being called into action anywhere. We'll get it to do its work when a button is clicked.
To call a Method, you just do this:
AddUp();
So you type the name of your Method, along with the round brackets. The semicolon ends the line of code, as normal.
So add that line to your button that Adds Up:
Call the Method
Run your programme and test it out. Click the Add Up button and you should see the message box display.
What happens is that the button calls the AddUp Method into action. C# then trots off and executes all of the code for your Method. It then comes back to the line where it was called, ready to execute any other code you may have for your button.

Passing values to your C# Methods

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:
The method has two parameters
So we've added two parameters between the round brackets of AddUp. A parameter is set up just like an ordinary variable. You start with the variable type (int, string, bool, etc.) then a space. After the space, you need to come up with a name for your parameter. We've called our first parameter firstNumber. But we could have called it almost anything. If you want more than one parameter, you separate them with commas. We've added a second parameter and called it secondNumber. Both parameters have been set up as type int. They're going to hold numbers, in other words.
We can use these parameters in the code for the Method. Adapt your AddUp code so that it's like ours below:
Change your code
So we've set up a new int variable called answer. We're then adding up the variables firstNumber and secondNumber. The result goes in the new variable. The message box displays what is in the variable called answer.
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:
Argument error
This error message can be translated as "You have no Method called AddUp that takes zero arguments." When you're calling a Method into action, you need to use the same number of parameters (now called arguments instead) as when you set it up. We set up our Method to take two values, firstNumber and secondNumber. So we need to use two values when we call the Method.
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:
The method now has two arguments
So we've now typed two number between the round brackets, 15 and 5. The first value you type will get handed to parameter one of your Method, the second value will get handed to parameter two, and so on. The picture below might clear things up, if all of that is a little confusing:
Arguments and Parameters
So the Method itself has two parameters. When it is being called in the button code there are now two arguments, once for each parameter.
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:
Change your code
Now, the values between the round brackets are no longer numbers that we've just typed in there. Instead, we're getting the values from the text boxes, and placing them between the round brackets. Note the comma separating the two values.
You can also do this:

We're now putting the values from the text boxes into two new variables, called number1 and number2. When we call the Method, we can use these variable names:
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.

Getting values back from C# Methods

The Method we set up used the keyword void. We used void because we didn't want anything back from the Method. But quite often you will want something back from your Methods.
What we'll do now is to use the Subtract button and deduct one text box number from the other. We'll set up another Method called Subtract. This time, we'll set it up so as to return an answer.
If you want to return a value from your Methods, you can't use the keyword void. Simply because void means "Don't return an answer". Instead of using void, we'll use the keyword int.
Add the following Method to your code, either above or below the AddUp Method:
A Method that returns a value
If you add a few comments, your coding window should look like ours:
What your coding window should look like
So we have one button and two Methods. Before we explain the new Method, double click the Subtract button on your form to get at its code. Then add the following:
Add this code
We'll explain how this button code works in a moment. But run your programme and you should see a message box appear when you click your Subtract button. Hopefully it will have the right answer!
Now have a look at the first line of the new Method:
private int Subtract( int firstNumber, int secondNumber)
The part in round brackets is exactly the same as before, and works the same way - set up the Method to accept two integer values. What's new is this part:
private int Subtract
Subtract is just the name of the Method, something we came up with ourselves. Before the Method name, however, we have two new keywords - private and int.
What we want our Method to do is to bring back the answer to our subtraction. The answer will obviously be a number. And that's why int comes before the Method name: we want the answer to the Subtract Method to be an integer. If you want to return values from your Methods they need what's called a return type. This is a variable like int, float, string, bool, etc. What you're telling C# to do is to return an int (or a bool, or a float).
Have a look at the whole Method again:

A Method that returns a value
Notice the final line:
return answer;
This means, "return whatever is inside of the variable called answer."
But where is C# returning to? Here's the code for the Subtract button again. The important line is in blue bold below:
private void button2_Click(object sender, EventArgs e)
{
int number1;
int number2;
int returnValue = 0;
number1 = int.Parse(textBox1.Text);
number2 = int.Parse(textBox2.Text);
returnValue = Subtract(number1, number2);
MessageBox.Show(returnValue.ToString());
}
When you click the button on the form, C# moves down line by line. When it gets to this line:
returnValue = Subtract( number1, number2 );
it will trot off and locate the Method called Subtract. It will then try to work out the code for the Method. Once it has an answer, it comes back to the same place. We have the call to the Method after an equals sign. Before the equals sign we have a new integer variable, which we've called returnValue. C# will store the answer to the Subtract Method inside of this returnValue variable. In other words, it's just like a normal variable assignment: work out the answer on the right of the equals sign, and store it on the left. In case that's not clear, these diagrams may help:
Step 1
Step 2
Step 3
Step 4
Step 5
After those steps, C# then drops down to the next line, which for us is a message box.
It can be tricky trying to follow what the method is doing, and what gets passed back. But just remember these points:

  • To set up a Method that returns a value, use a return type like int, float, bool, string, etc
  • Use the keyword return, followed by the answer you want to have passed back
  • Store the answer to your Method in another variable, which should come before an equals sign
One thing we haven't explained is why we started our Method with the word private.
Private refers to which other code has access to the Method. By using the private keyword you're telling C# that the Method can't be seen outside of this particular class. The class in question is the one at the top of the code, for the form. This one:
public partial class Form1 : Form
An alternative to private is public, which means it can be seen outside of a particular class or method. (There's also a keyword called static, which we'll cover later in the course.)


 


 

0 comments:

Post a Comment