Writing Methods

   

Writing Methods

graphics/newterm.gif

After you've created the class(es) in which to store your code, you can begin writing methods. A method is a discrete set of code that can be executed. Methods are much like events, but rather than being executed by a user interacting with a form or control, methods are executed when called by a code statement.

The first thing to keep in mind is that every method should perform a specific function, and it should do it very well. You should avoid creating methods that perform many tasks . As an example of the use of methods, consider that you want to create a set of code that, when called, draws an ellipse on a form. You also want a second method to clear the form. If you placed both sets of code into the same method, the ellipse would be drawn and then would immediately be erased. By placing each set of code in its own method, you can draw the ellipse by calling one method and then erase it at any time by calling the other method. By placing these routines in a class rather than attaching them to a specific form, you also make the methods available to any form that may need them.

There are two types of methods in C#:

  • Methods that return a value

  • Methods that do not return a value (void)

There are many reasons to create a method that returns a value. For example, a method can return true or false, depending on whether it was successful in completing its task. You could also write a method that accepts certain parameters (data passed to the method, in contrast to data returned by the method) and returns a value based on those parameters. For example, you could write a method that lets you pass it a sentence, and in return it passes back the number of characters in the sentence . The possibilities are limited only by your imagination . Just keep in mind that a method doesn't have to return a value.

Declaring Methods That Don't Return Values

Because you've already created a class, you're ready to create methods (to create a method, you first declare it within a class).

Position the cursor to the right of the closed brace ( } ) that signifies the end of the public clsStaticExample block and press Enter to create a new line. Enter the following three statements:

 public static void DrawEllipse(System.Windows.Forms.Form frm) { } 

Next , position your cursor to the right of the open brace ( { ) and press Enter to create a new line between the two braces. This is where you'll place the code for the method.

The declaration of a method (the statement used to define a method) has a number of parts . The first word, public, is a keyword (a word with a special meaning in C#). The keyword public defines the scope of this method, designating that the method can be called from code contained in modules other than the one containing the defined method (scope is discussed in detail in the next hour ). You can use the keyword private in place of public to restrict access of the method to code only in the module in which the method resides.

The word static is another C# keyword. As mentioned earlier, static members belong to a class as a whole, not to a specific instance of a class. This will allow the DrawEllipse() method to be accessed from other classes without having to instantiate an clsStaticExample object.

The word void is another C# keyword. The void keyword is used to declare a method that doesn't return a value. Later in this hour, you will learn how to create methods that do return values.

The third word, DrawEllipse, is the actual name of the method and can be any string of text you want it to be. Note, however, that you can't assign a name that is a keyword, nor can you use spaces within a name. In this example, the method is going to draw an ellipse on the form, so you used the name DrawEllipse. You should always give method names that reflect their purpose. You can have two methods with the same name only if they have different scope (discussed in the next hour).

graphics/bulb.gif

Some programmers prefer the readability of spaces in names, but in many instances, such as when naming a method, spaces can't be used. A common technique is to use an underscore (_) in place of a space, such as in Draw_Ellipse. This isn't a recommended practice, however.

graphics/newterm.gif

Immediately following the name of the method is a set of parentheses surrounding some text. Within these parentheses you can define parameters ”data to be passed to the method by the calling program. In this example, you've created a parameter that accepts a reference to a form. The routine will draw an ellipse on whatever form is passed to the parameter.

graphics/bookpencil.gif

Parentheses must always be supplied, even when a procedure doesn't accept any parameters (in which case nothing is placed between the parentheses).

Add the following code to your DrawEllipse method:

 System.Drawing.Graphics objGraphics; System.Drawing.Rectangle recDrawRectangle; recDrawRectangle = frm.DisplayRectangle; recDrawRectangle.Inflate(-5, -5); objGraphics = frm.CreateGraphics(); objGraphics.Clear(System.Drawing.SystemColors.Control); objGraphics.DrawEllipse(System.Drawing.Pens.Blue, recDrawRectangle); objGraphics.Dispose(); 

Much of this code is similar to a code example discussed in Hour 3, "Understanding Objects and Collections," so I'm not going to go over it in detail. Basically, this routine creates a rectangle with the same dimensions as the client rectangle of the supplied form. Then, the Inflate method is used to reduce the size of the rectangle by 5 pixels in each dimension. Finally, a graphics object is created and set to reference the client area of the supplied form, and a rectangle is drawn within the boundaries of the rectangle.

When you've finished entering your code, it should look like that in Figure 11.3.

Figure 11.3. All code for a method must reside between the open and close braces of the method.

graphics/11fig03.jpg


Now you're going to create a procedure that erases the ellipse from a form. Place the caret (cursor) at the end of the closing brace (} ) for the DrawEllipse() method and press enter to create a new line. Enter the following three statements:

 public static void ClearEllipse(System.Windows.Forms.Form frm) { } 

Add the following line of code to the ClearEllipse() method on a new line between the opening and closing braces:

 frm.Refresh(); 

This single line of code forces the designated form to refresh itself. Because the ellipse that was drawn by the first procedure isn't part of the form (it was simply drawn onto the form), the ellipse is cleared.

Declaring Methods That Return Values

graphics/newterm.gif

The two methods you've created so far don't return values. You're now going to declare a method that returns a value. Here's the general syntax for the method you will create:

 [modifiers] datatype MethodName(parameters) 

You'll notice one key difference between declaring a method that doesn't return a value and declaring one that does: you have to define the data type of the value returned. Previously, you used the keyword void to declare that no value was being returned. Data types are discussed in detail in the next hour, so it's not important that you fully understand them now. It is important, however, that you understand what is happening.

The data type entered before the method name denotes the type of data returned by the method. The method that you're about to enter returns a numeric value of type integer. If the method were to return a string of text, it would be declared as string. It is very important that you declare the proper data type for your functions.

Position the cursor to the right of the closing brace for the ClearEllipse() method, press Enter to create a new line, and enter the following three statements:

 public static int ComputeLength(string strText) { } 

Add the following code to a new line between the two braces:

 return strText.Length; 

When you create a method that returns a value, you use the C# keyword return to return whatever value you want the method to return. In this example, you're using the built-in Length() method of the string class to determine the number of characters within the string that's passed to the method. This value is returned as the value of the method. (You could, of course, avoid writing the function altogether and just use the String.Length() method in the calling code, but this makes a good example.) Your methods should now look like the one in Figure 11.4.

Figure 11.4. Classes often contain many methods.

graphics/11fig04.jpg



   
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