Jump to content

User:Foxall/11

Ka Wiktionary

Hour 11. Creating and Calling Methods

[wax ka badal]

You've now spent about 11 hours building the basic skills necessary to navigate C# and to create an application interface. Creating a good interface is extremely important, but it's only one step toward creating a Windows program. After you've created the basic interface of an application, you need to enable the program to do something. The program may perform an action all on its own, or it may perform actions based on a user interacting with the interface�either way, to make your application perform tasks, you write C# code. In this hour, you'll learn how to create sets of code (called classes), and how to create and call isolated code routines (called methods).

The highlights of this hour include the following:

  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch11lev1sec1.htm#ch11lev1sec1 Creating static class members]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch11lev1sec2.htm#ch11lev1sec2 Creating methods]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch11lev1sec4.htm#ch11lev1sec4 Calling methods]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch11lev1sec5.htm#ch11lev1sec5 Exiting methods]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch11lev1sec4.htm#ch11lev2sec3 Passing parameters]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch11lev1sec4.htm#ch11lev2sec4 Avoiding recursive methods]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch11lev1sec6.htm#ch11lev1sec6 Working with tasks]

Creating Class Members

[wax ka badal]
graphics/newterm.gif A class is a place to store the code you write. Before you can begin writing C# code, you must start with a class. As mentioned in previous hours, a class is used as a template to create an object (which may have properties and/or methods). Properties and methods of classes can be either instance members or static members. Instance members are associated with an instance of a class�an object created from a class using the keyword new. On the other hand, static members belong to the class as a whole, not to a specific instance of a class. You've already worked with one class using instance members to create a form (refer to [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05.htm#ch05 Hour 5], "Building Forms�Part I, for more information).When you double-click an object on a form, you access events that reside in the form's class module.

Other languages, such as Visual Basic, differentiate between class methods and public methods that are globally available outside of a class. C# requires all methods to exist in the context of a class, but a globally available method can be achieved by defining static methods in your class. Static methods are always available regardless of whether an instance of the class exists. In fact, you can't access a static member through an instance of a class, and attempting to do so results in an exception (error).

graphics/bookpencil.gif Classes are used as templates for the instantiation of objects. I discuss the specifics of creating objects in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch17.htm#ch17 Hour 17], "Designing Objects Using Classes." Most of the techniques discussed in this hour apply to class modules with instance members (methods that are part of an instantiated object), but I'm going to focus this discussion on static members because they are easier to use (you can create and use static methods without getting into the complications of creating objects).

Although you could place all your program's code into a single class module, it's best to create different modules to group different sets of code. In addition, it's best not to place code that isn't specifically related to a form within a form's class module; place such code in the logical class or in a specialized class module.

graphics/bookpencil.gif The current development trend centers on object-oriented programming, which revolves around class modules. I'll give you a primer on object-oriented programming in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch17.htm#ch17 Hour 17], but this is a very advanced topic so I won't be covering it in detail. I highly recommend that you read a dedicated object-oriented book, such as 'Sams Teach Yourself Object-Oriented Programming in 21 Days, after you are comfortable with the material in this book.

One general rule for using static members is that you should create classes to group related sets of code. This isn't to say you should create dozens of classes. Rather, group related methods into a reasonably sized set of classes. For instance, you might want to create one class that contains all your printing routines and another that holds your data-access routines. In addition, I like to create a general-purpose class in which to place all the various routines that don't necessarily fit into a more specialized class.

Start C# now and create a new Windows Application project named Static Methods.

Change the name of the default form to fclsExample, set its Text property to Method Example, and set the Main() entry point of the project to reference fclsExample instead of Form1. Change the Size property of the form to 371, 300. Next, add a new class to the project by choosing Add Class from the Project menu. C# then displays the Add New Item dialog box, as shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#ch11fig01 Figure 11.1].

Figure 11.1. All new project items are added using this dialog box.

graphics/11fig01.jpg

Note that this is the same dialog box used to add new forms. Change the name of the class to clsStaticExample.cs and click Open. C# then creates the new class and positions you in the code window�ready to enter code (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#ch11fig02 Figure 11.2]).

Figure 11.2. Classes have no graphical interface, so you always work with them in the code editor.

graphics/11fig02.jpg

Save your project now by clicking Save All on the toolbar.

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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03.htm#ch03 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#ch11fig03 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#ch11fig04 Figure 11.4].

Figure 11.4. Classes often contain many methods.

graphics/11fig04.jpg

Creating the User Interface of Your Project 

Now that you've written this example's procedures, you need to create the interface for the project. Click the Form1.cs [Design] tab in the IDE to display the form designer for the default form.

You'll need three buttons on this form�one to call each of your methods. Add the first button to the form by double-clicking the Button icon in the toolbox and then set its properties as follows:

Property Value
Name btnDrawEllipse
Location 0,0
Size 80,23
Text Draw Ellipse

Add a second button to the form and set its properties as follows:

Property Value
Name btnClearEllipse
Location 283,0
Size 80,23
Text Clear Ellipse

Finally, add the third button to the form and set its properties as follows:

Property Value
Name btnComputeLength
Location 0,250
Size 100,23
Text Compute Length

The last control you need to add to your form is a text box. When the user clicks the Compute Length button, the button's Click event will call the ComputeLength function, passing it the text entered into the text box. It will then display the length of the text in the Output window (this works only when running in the IDE, not when compiled as an application).

graphics/bookpencil.gif The Output window is a Visual Studio design window to which you can print text. I use the Output window a lot in examples throughout the remaining hours. When you send text to the Output window, Visual Studio ensures that the Output window is visible. You can display it at any time while working in the IDE by choosing Other Windows from the View menu and then selecting Output. Be aware that the Output window is not available to a compiled component.

Add a text box to the form by double-clicking the Textbox icon in the toolbox. Set the new text box's properties as follows:

Property Value
Name txtInputForLength
Location 110,250
Text (make blank)

Your form should now look like the one shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#ch11fig05 Figure 11.5]. You're now ready to write the C# code to call your methods.

Figure 11.5. This form is not all that attractive, but it's functional enough for our purposes.

graphics/11fig05.jpg

>

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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#ch11fig06 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch07.htm#ch07 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch07.htm#ch07 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch13.htm#ch13 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#ch11fig07 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#ch11fig08 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 work�parameters 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12.htm#ch12 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 parentheses�the 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. [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12.htm#ch12 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#ch11fig09 Figure 11.9].

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.

Exiting Methods 

Ordinarily, code within a method executes from beginning to end�literally. However, when a return statement is reached, execution immediately returns to the statement that made the method call; you can force execution to leave the method at any time by using a return statement. If C# encounters a return statement, the method terminates immediately, and code returns to the statement that called the method.

As you build your applications, you'll find that the number of methods and classes expands rather quickly. At times, you'll realize that a method isn't finished or that you had to use a "hack" (a less-desirable solution) to solve a problem. You'll need an easy way to keep these things straight so that you can revisit the code as needed. You'll learn a powerful way to do this in the next section.

>

Working with Tasks

One of the most exciting IDE enhancements from previous versions of Visual Studio, in my opinion, is the new Task List. Tasks are really all about managing code. If your Task List window isn't displayed, show it now by choosing Show Tasks from the View menu and then choosing All. Tasks are used to keep track of critical spots in code or things that need to be done. C# automatically creates some tasks for you, and you can create your own as needed.

One instance in which C.htm# creates tasks is when your code has compile (build) errors. Because C# knows the exact error and the offending statement, it creates an appropriate task. [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#ch11fig10 Figure 11.10] shows the Task List containing a build error. Notice how the task's description tells you the exact problem. Double-clicking a system-generated task takes you directly to the related statement (double-clicking a task that you created has a different effect, as discussed shortly). If the task exists in a class that isn't loaded, C# loads the class and then takes you to the statement. This greatly simplifies the process of addressing compile errors in code; you can simply work through the list of tasks rather than compile, fix an error, try compiling again, fix the next error, and so on.

Figure 11.10. Tasks help you keep track of critical spots in code.

graphics/11fig10.jpg

In addition to system-generated tasks, you can create your own tasks as often and wherever needed. In the past, it was common to place certain comments such as "TODO" in code where you needed to address something. These comments often were forgotten. When you wanted to address the issues, you had to perform a text search in your code. This was a highly inefficient process.

Now you can create a task wherever you need to. Creating a task is easy. Right-click the code statement to which you want to attach the task and choose Add Task List Shortcut from the context menu. C# creates a task shortcut at the statement (as indicated by a blue arrow in the left margin of the code window) and adds the task to the Task List window. The default description for the next task is the actual code statement you flagged (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#ch11fig11 Figure 11.11]). To change this text, click the description in the Task List to put it in Edit mode and then change the text. To go directly to the statement to which a task is attached, double-click the shortcut arrow next to the task in the Task List (the arrow is the same one that appears in the left margin of the code window).

Figure 11.11. Tasks make it easy to track issues that need to be addressed.

graphics/11fig11.jpg

graphics/bookpencil.gif Another way to create a task is to insert a comment that literally starts with TODO:�Visual Studio .NET will then automatically create a task using the comment.

You don't have to attach a task to a code statement. To create a task that isn't attached to code, click the first row of the Task List. The default text Click here to add a new task goes away, and you're free to enter the description for your new task.

To delete a task you created, click once on the task in the Task List to select it, and then right-click the task and choose Delete from the context menu. You can't delete a task that was created by C# as a result of a build error�you must correct the error to make the task go away.

Tasks are an incredibly simple, yet useful, tool. I highly encourage you to use them in your development.

>

Summary

In this hour, you learned how a method is a discrete set of code designed to perform a task or related set of tasks. Methods are where you write C# code. Some methods may be as short as a single line of code, whereas others are pages in length. You learned how to define methods and how to call them. Creating and calling methods is critical to your success in programming with C#; be sure to avoid creating recursive methods! Because you use methods so often, they'll become second nature to you in no time.

Classes are used to group methods. In this hour, I focused on the class module (which is little more than a container for methods) and static methods. Remember to group related methods in the same class and to give each class a descriptive name. In [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch17.htm#ch17 Hour 17], you'll build on your experience with classes and methods and work with instance classes.

Finally, you learned about Visual Studio's new Task List feature. You now know that C# creates some tasks for you but that you are free to create tasks as you see fit. You learned how to easily jump to a statement that's related to a task and how to create tasks that aren't related to a specific code statement. The Task List is a powerful tool to have in your arsenal, and I encourage you to use it.

>

Q&A

[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#qad1e37796 Q1:] Do I need to pay much attention to scope when defining my methods?
A1: It may be tempting to create all your methods as public static, but this is bad coding practice for a number of reasons. For one thing, you will find that in larger projects, you'll have methods with the same name that do slightly different things. Usually, these routines are relevant only within a small scope. If the method isn't needed at the public level, don't define it for public access.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/11.htm#qad1e37824 Q2:] How many classes is a "reasonable" amount?
A2: This is hard to say. There really is no right answer. Instead of worrying about an exact count, you should strive to make sure that your classes are logical and that they contain only appropriate methods and properties.
>

Workshop

The Workshop is designed to help you anticipate possible questions, review what you've learned, and get you thinking about how to put your knowledge into practice. The answers to the quiz are in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01.htm#app01 Appendix A], "Answers to Quizzes/Exercises."

 Quiz
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec11.htm#ch11ans01 1:] What are the entities called that are used to house methods?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec11.htm#ch11ans02 2:] True or False: To access methods in a class module, you must first create an object.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec11.htm#ch11ans03 3:] Data that has been passed into a method by a calling statement is called a
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec11.htm#ch11ans04 4:] To pass multiple arguments to a method, separate them with a
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec11.htm#ch11ans05 5:] The situation in which a method or set of methods continue to call each other in a looping fashion is called
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec11.htm#ch11ans06 6:] How do you attach a task to a code statement?
Exercises
  1. Create a method as part of a form that accepts a string and outputs to the string. Add code to the TextChanged event of a text box to call the procedure, passing the contents of the text box as the argument.
  2. Create a single method that calls itself. Call this method from the Click event of a button and observe the error that results.