Calling Methods

   

Calling Methods

Calling a method is fairly simple. However, just as methods that return values are declared differently from methods that do not, calling these two types of methods differs as well. You're first going to write code to call the two methods you declared as void (methods that don't return values). Double-click the Draw Ellipse button to access its Click event and take a look at the event declaration:

 private void btnDrawEllipse_Click(object sender, System.EventArgs e) { } 

As you can see, event handlers are methods. The only real difference is that event methods are called automatically in response to the user doing something, rather than being called by code you write. In this case, the btnDrawEllipse_Click() event is called when the user clicks the btnDrawEllipse button. This method is declared as private, so only methods within this module could call this method (yes, you can call event methods). Add the following statement to this Click event:

 clsStaticExample.DrawEllipse(this); 

To call the DrawEllipse method, you must precede it with the name of the class in which it is defined. The method name and parentheses always come next . If the method expects one or more parameters, place them within the parentheses. In this case, the DrawEllipse() procedure expects a reference to a form. By specifying the keyword this, you're passing a reference to the current form.

graphics/bulb.gif

When you type in the class name clsStaticExample followed by a period, C# displays the methods defined for the clsStaticExample class. Also, notice that when you type in the left parenthesis for the DrawEllipse() method , C# displays a ToolTip showing the parameters expected by the method (see Figure 11.6). It can be difficult to remember the parameters expected by all methods (not to mention the proper order in which to pass them), so this little feature will save you a great deal of time and frustration.

Figure 11.6. C# displays the parameters expected of a method.

graphics/11fig06.jpg


You're now going to place a call to the ClearEllipse() method in the Click event of the Clear Ellipse button. Display the form in Design view again and double-click the Clear Ellipse button to access its Click event. Add the following statement:

 clsStaticExample.ClearEllipse(this); 

All that's left to do is add code that computes the length of the string entered by the user. Again, display the form in Design view. Double-click the Compute Length button to access its Click event and enter the following statements (recall from Hour 7, "Working with Traditional Controls," that Debug.WriteLine() sends text to the Output window.):

 int intLength; intLength = clsStaticExample.ComputeLength(txtInputForLength.Text); System.Diagnostics.Debug.WriteLine("length = " + intLength); 

The first line creates a new variable to hold the return value of the ComputeLength() method (the next hour covers variables ). The second statement calls the ComputeLength() method. When calling a method that returns a value, think of the method in terms of the value it returns. For example, when you set a form's Height property, you set it with code like this:

 MyForm.Height = 200; 

This statement sets a form's height to 200. Suppose you had a method that returned a value that you wanted to use to set the form's Height property. Thinking of the method in terms of the value it returns, you could replace the literal value with a method call, as in the following:

 MyForm.Height = MyClass.MyMethod(); 

Try to look at the statement you just entered using this way of thinking. When you do, you see that the statement in this example really says, "Set the variable intLength equal to the value returned by the method ComputeLength()." If ComputeLength() returned the value 20, for example, the line of code would behave as though it were written like this:

 intLength = 20; 

When calling methods, you must treat the method call the same as you would treat the literal value returned by the method. This often means placing a method call on the right side of an equal sign.

The last line of code you entered outputs the result of the method call to the Output window in the IDE (refer to Hour 7). The text "length =" and the value of intLength are concatenated (joined together), to produce one string of text that gets displayed. You'll learn about concatenation in Hour 13, "Performing Arithmetic, String Manipulation, and Date/Time Adjustments." The project is now complete. Click Save All on the toolbar to save your work, and then press F5 to run the project. Click the Draw Ellipse button and an ellipse is drawn on the form (see Figure 11.7).

Figure 11.7. Clicking the button calls the method that draws the ellipse in the house that Jack built.

graphics/11fig07.jpg


Here's what is happening when you click the Draw Ellipse button:

  1. The Draw Ellipse button's Click event is triggered.

  2. The method call statement within the Click event is executed.

  3. Code execution jumps to the DrawEllipse() method.

  4. All code within the DrawEllipse() method gets executed.

  5. Execution returns to the Click event.

Click the Clear Ellipse button now to clear the form. When you click this button, the following occurs:

  1. The Clear Ellipse button's Click event is triggered.

  2. The method call statement within the Click event is executed.

  3. Code execution jumps to the ClearEllipse() method.

  4. All code within the ClearEllipse() method gets executed.

  5. Execution returns to the Click event.

Finally, enter some text into the text box and click the Compute Length button. Here's what happens:

  1. The Compute Length button's Click event is triggered.

  2. The reference to the ComputeLength method causes code execution to jump to that method.

  3. The ComputeLength() method determines the length of the string. This value is passed back as the result of the method.

  4. Execution returns to the Click event.

  5. The result of the method is placed in the variable intLength.

  6. The rest of the code within the Click event executes. The final result is the length of the string, which is printed in the Output window (see Figure 11.8).

    Figure 11.8. System.Diagnostics.Debug.WriteLine sends text to the Output window.

    graphics/11fig08.jpg


Passing Parameters

Parameters are used within a method to allow the calling code to pass data into the method; methods help eliminate module and global variables. You've already seen how parameters workparameters are created within the parentheses of a method declaration. A parameter definition consists of the data type and a name for the parameter, as shown here:

 public static void MyMethod(string strMyStringParameter) 
graphics/bookpencil.gif

After you've read about variables in Hour 12, "Using Constants, Data Types, Variables, and Arrays," this structure will make a lot more sense. Here, I just want you to get the general idea of how to define and use parameters.

You can define multiple parameters for a method by separating them with a comma, like this:

 public static void MyMethod(string strMyStringParameter,                             int intMyIntegerParameter) 
graphics/newterm.gif

A calling method passes data to the parameters by way of arguments. This is mostly a semantic issue; when defined in the declaration of a method, the item is called a parameter. When the item is part of the statement that calls the method, it's called an argument. Arguments are passed within parenthesesthe same as parameters are defined. If a procedure has multiple arguments, you separate them with commas. For example, you could pass values to the method just defined using a statement such as this:

 MyClass.MyProcedure("This is a string", 11); 

The parameter acts like an ordinary variable within the method. Hour 12 discusses variables in depth. For now, just realize that variables are storage entities whose values can be changed. In the call statement shown previously, I sent literal values to the procedure. I could have also sent the values of variables like this:

 MyClass.MyProcedure(strAString, intAnInteger); 
graphics/newterm.gif

An important thing to note about passing variables in C# is that parameters are passed by value rather than by reference. When passed by value, the method receives a copy of the data; changes to the parameter don't affect the value of the original variable. When passed by reference, the parameter is actually a pointer to the original variable. Changes made to the parameter within the method propagate to the original variable. To pass a parameter by reference, you preface the parameter definition with the keyword ref as shown here:

 public static void MyMethod(ref string strMyStringParameter,                             int intMyIntegerParameter) 

Parameters defined without ref are passed by value; this is the default behavior of parameters in C#. Therefore, in this declaration, the first parameter is passed by reference, whereas the second parameter is passed by value.

Avoiding Recursive Methods

It's possible to call methods in such a way that a continuous loop occurs. Consider the following procedures:

 public static void DoSomething() {     DoSomethingElse(); } public static void DoSomethingElse() {    DoSomething(); } 

Calling either of these methods produces an infinite loop of methods calls and results in the error shown in Figure 11.9.

Figure 11.9. Infinite recursion results in a Stack Overflow Exception (error).

graphics/11fig09.jpg


graphics/newterm.gif

This endless loop is known as a recursive loop. Without getting too technical, C# allocates some memory for each method call in an area known as the stack. Only a finite amount of space is on the stack, so infinite recursion eventually uses all the available stack space and an exception occurs. This is a serious error, and steps should be taken to avoid such recursion.

Legitimate uses exist for recursion, most notably in the use of algorithms such as those used in calculus. Deliberate recursion techniques don't create infinite recursion, however. There is always a point where the recursion stops (hopefully, before the stack is consumed). If you have an interest in such algorithms, you should consider reading a book dedicated to the subject.


   
Top


Sams Teach Yourself C# in 24 Hours
Sams Teach Yourself Visual Basic 2010 in 24 Hours Complete Starter Kit (Sams Teach Yourself -- Hours)
ISBN: 0672331136
EAN: 2147483647
Year: 2002
Pages: 253
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net