7 c# .net methods

Upload: oliviaecaterina

Post on 04-Jun-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 7 C# .NET Methods

    1/13

    Understanding C# Methods

    So far, all of your programming code has gone between the curly brackets of buttons. Butthis 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. hink about the calculatorprogramme you have been working on. !ou can have one Method " a chunk of code# to

    add up, one to subtract, another one to divide, and a fourth Method to multiply. he idea

    is that when you want to add up, you just call the Add $p Method into action.

    o get you started with Methods, we%ll create a simple programme that takes twonumbers from te&t bo&es. 'e%ll have four buttons, one to add up, one to subtract, one to

    divide, and one to multiply. 'e%ll use Methods to do the calculating. (ff we go then)

    *reate a new *+ project, and design the following form

    !ou can keep the buttons and te&t bo&es on their default names "button-, button,

    te&tbo&-, te&tbo&, etc.#

    /ouble click the Add $p button to open up the coding window. he cursor will beflashing inside of the button code. 0owever, you create Methods outside of any other

    code. So move the cursor after the final curly bracket of the button code. hen hit your

    enter key a few times to give yourself some space. ype the following

    void Add$p"#1

    -

  • 8/13/2019 7 C# .NET Methods

    2/13

    MessageBo&.Show"2Add $p 0ere2#3

    return;

    4

    !our coding window will then look like ours below

    Methods can return a value, such as the answer to the addition. But they don%t have to.

    (ur Method above just displays a message bo& when it is called into action. If you don%twant 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. 'e%ve called

    ours AddUp. But they are just the same as variable names, and you call them almostanything you like. "he same rules apply to naming Methods as they do to naming

    5ariables.#

    After coming up with a name for your Method, you type a pair of round brackets. !oucan 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. he code for your Method

    goes between the curly brackets. 6or us, this was just a Message Bo&.

    Before the final curly bracket, we%ve typed the word return, followed by a semicolon.

    his is not necessary, if you%ve set your Method up as void, since you don%t want it toreturn anything you just want it to get on with its job. 'e%ve added the return keyword

    because it%s just standard practice. But when *+ sees the return keyword, it will break out

    of your Method. If you type any code after that, it won%t get e&ecuted. "!ou%ll see a

    different way to use the return keyword when we want to get something back from aMethod.#

    Calling your Methods

  • 8/13/2019 7 C# .NET Methods

    3/13

    (ur Method is not doing much good at the moment, since it%s not being called into action

    anywhere. 'e%ll get it to do its work when a button is clicked.

    o call a Method, you just do this

    AddUp();

    So you type the name of your Method, along with the round brackets. he semicolon

    ends the line of code, as normal.

    So add that line to your button that Adds $p

    7un your programme and test it out. *lick the Add $p button and you should see the

    message bo& display.

    'hat happens is that the button calls the AddUpMethod into action. *+ then trots offand e&ecutes all of the code for your Method. It then comes back to the line where it was

    called, ready to e&ecute any other code you may have for your button.

    In the ne&t part, you%ll see how to pass values to your Methods.

    8

  • 8/13/2019 7 C# .NET Methods

    4/13

    Passing values to your C# Methods

    !ou can hand values over to your Methods. he Method can then use these values in its

    code. 6or us, we want to get two numbers from the te&t bo&es, and then add them up. hetwo values from the te&t bo&es, then, need to be handed over to our Method. he code to

    add up will go between the curly brackets of the AddUpMethod.

    o hand values over to your Methods, you place them between the round brackets. hese

    are called parameters. "!ou%ll also hear the term arguments, often used to mean the samething. here is a subtle difference, however, which you%ll see shortly. It%s not crucial that

    you learn the difference, though)#

    *hange your Method to this

    So we%ve added two parameters between the round brackets of Add$p. A parameter is set

    up just like an ordinary variable. !ou 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.

    'e%ve called our first parameterfirstNumber. But we could have called it almost

    anything. If you want more than one parameter, you separate them with commas. 'e%ve

    added a second parameter and called it secondNumber. Both parameters have been setup as type int. hey%re going to hold numbers, in other words.

    'e can use these parameters in the code for the Method. Adapt your Add$p code so that

    it%s like ours below

    So we%ve set up a new intvariable called anser. 'e%re then adding up the

    variables firstNumberand secondNumber. he result goes in the new variable. hemessage bo& displays what is in the variable called anser.

    9

  • 8/13/2019 7 C# .NET Methods

    5/13

    If you try to run your code now, however, you%ll get an error. here will be a wavy blue

    line under Add$p, along with a strange error message

    his error message can be translated as 2!ou have no Method called Add$p that takes

    :ero arguments.2 'hen you%re calling a Method into action, you need to use the samenumber of parameters "now called arguments instead# as when you set it up. 'e set up

    our Method to take two values, firstNumberand secondNumber. So we need to use two

    values when we call the Method.

    0ere%s the difference between an argument and a parameter It%s a parameter when you setup the values in the method3 It%s an argument when you%re calling it "passing the values to

    the Method#.

    *hange your button code to this

    So we%ve now typed two number between the round brackets, -; and ;. he first valueyou type will get handed to parameter one of your Method, the second value will get

    handed to parameter two, and so on. he picture below might clear things up, if all of thatis a little confusing

    So the Method itself has two parameters. 'hen it is being called in the button code there

    are now two arguments, once for each parameter.

    7un your programme again and there shouldn%t be any errors. 'hen you click your

    button, you should see the answer to the addition.

    ;

  • 8/13/2019 7 C# .NET Methods

    6/13

    0alt your programme, and change your button code to this

  • 8/13/2019 7 C# .NET Methods

    7/13

    $etting values bac% from C# Methods

    he Method we set up used the keyword void. 'e used void because we didn%t want

    anything back from the Method. But ?uite often you will want something back from yourMethods.

    'hat we%ll do now is to use the Subtract button and deduct one te&t bo& number from the

    other. 'e%ll set up another Method called Subtract. his 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 2/on%t return an answer2. Instead of using void, we%ll use the

    keyword int.

    Add the following Method to your code, either above or below the Add$p Method

    If you add a few comments, your coding window should look like ours

    @

  • 8/13/2019 7 C# .NET Methods

    8/13

    So we have one button and two Methods. Before we e&plain the new Method, double

    click the&ubtractbutton on your form to get at its code. hen add the following

  • 8/13/2019 7 C# .NET Methods

    9/13

    'e%ll e&plain how this button code works in a moment. But run your programme and you

    should see a message bo& appear when you click your Subtract button. 0opefully it will

    have the right answer)

  • 8/13/2019 7 C# .NET Methods

    10/13

    returnanswer3

    his means, 2return whatever is inside of the variable called answer.2

    But where is *+ returning toD 0ere%s the code for the Subtract button again. he

    important line is in blue bold below

    private void button"'Clic%(obect sender ventArgs e)

    *

    int number!;

    int number";

    int return+alue , -;

    number! , int.Parse(te/t0o/!.1e/t);

    number" , int.Parse(te/t0o/".1e/t);

    return+alue , &ubtract(number! number");

    Message0o/.&ho(return+alue.1o&tring());

    2

    'hen you click the button on the form, *+ moves down line by line. 'hen it gets to this

    line

    return+alue , &ubtract( number! number" );

    it will trot off and locate the Method called &ubtract. It will then try to work out the code

    for the Method. (nce it has an answer, it comes back to the same place. 'e have the callto the Method after an e?uals sign. Before the e?uals sign we have a new integer variable,

    which we%ve called return+alue. *+ will store the answer to the Subtract Method inside

    of this return5alue variable. In other words, it%s just like a normal variable assignmentwork out the answer on the right of the e?uals sign, and store it on the left. In case that%s

    not clear, these diagrams may help

    -E

  • 8/13/2019 7 C# .NET Methods

    11/13

    --

  • 8/13/2019 7 C# .NET Methods

    12/13

    After those steps, *+ then drops down to the ne&t line, which for us is a message bo&.

    It can be tricky trying to follow what the method is doing, and what gets passed back. Butjust remember these points

    o set up a Method that returns a value, use a return type

    like int, float, bool, string, etc

    $se 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 beforean e?uals sign

    (ne thing we haven%t e&plained is why we started our Method with the word private.

    Frivate refers to which other code has access to the Method. By using the private

    keyword you%re telling *+ that the Method can%t be seen outside of this particular class.

    he class in ?uestion is the one at the top of the code, for the form. his one

    -

  • 8/13/2019 7 C# .NET Methods

    13/13

    public partial class 3orm! 4 3orm

    An alternative to private is public, which means it can be seen outside of a particular

    class or method. "here%s also a keyword called static, which we%ll cover later in thecourse.#

    'e%ll leave Methods for now. But we%ll be using them a lot for the rest of this book) o

    help your understanding of the topic, try this e&ercise.

    /ercise 5

    Add two more Methods to your code, one to Multiply, and one to /ivide. Add code to

    your Multiply and /ivide buttons that uses your new Methods. 'hen you run your

    programme, all four buttons should work.

    Answer to G&ercise H

    In the ne&t section, we%ll move on and take a look at Arrays

    -8

    http://www.homeandlearn.co.uk/csharp/csharp_answers.html#exJhttp://www.homeandlearn.co.uk/csharp/csharp_answers.html#exJ