Lesson 4: Using Methods

Lesson 4: Using Methods

Methods do the work of classes and structures. They calculate values, update data, receive input, and perform all the manipulations that make up the behavior of a type. In this lesson, you will learn how to create methods, use parameters, and create constructors and destructors for your class.

After this lesson, you will be able to

  • Create a new method

  • Specify return types for your method

  • Specify input and output parameters for your method

  • Create a constructor and a destructor for your class

Estimated lesson time: 45 minutes

Adding Methods

You can add methods as members to your classes. Methods represent actions your class can take. Methods generally come in two varieties: those that return a value (functions in Visual Basic) and those that do not return a value (subs in Visual Basic). The following code shows an example of both kinds of methods:

Visual Basic .NET

Public Sub MySub() MessageBox.Show("This is a non-value returning method") End Sub ' Note that the underscore symbol ( _ ) is used in ' Visual Basic .NET to continue a line from one line to the next. Public Function Add(ByVal first as Integer, ByVal second as _ Integer) As Integer Dim Result as Integer Result = first + second Return Result End Function

Visual C# makes no distinction between methods that return a value and methods that do not. In either case, you must specify the return value type. If the method does not return a value, its return type is void. Here are examples of C# methods:

Visual C#

public void myVoidMethod() { MessageBox.Show("This method doesn't return a value"); } public int Add(int first, int second) { int Result; Result = first + second; return Result; }

Calling Methods

A method does not execute until it is called. You can call a method by referencing its name along with any required parameters. For example:

Visual Basic .NET

' This line calls the Rotate method, with two parameters Rotate(45, "Degrees")

Visual C#

// This line calls the Rotate method, with two parameters Rotate(45, "Degrees");

The Main method is a special case. It is called upon initiation of program execution. Destructors, another special case, are called by the runtime just prior to destruction of an object. Constructors, a third special case, are executed by an object during its initialization. These methods are discussed further later in this lesson.

Method Variables

Variables declared within methods are said to have method scope, which means that once the methods complete execution, they are destroyed and their memory reclaimed. They are said to have gone out of scope.

Variables within smaller divisions of methods have even more limited scope. For example, variables declared within a For-Next (for) loop are accessible only within the loop. The following example demonstrates this because the variable Y has gone out of scope:

Visual Basic .NET

Public Sub myMethod() Dim X as Integer For X = 1 to 100 Dim Y as Integer Y = X Next X ' This line causes an error Console.WriteLine(Y.ToString) End Sub

Visual C#

public void myMethod() { int X; for (X = 1; X < 101; X++) { int Y; Y = X; } // This line causes an error Console.WriteLine(Y.ToString()); }

Visual Basic allows you to create method variables that are not destroyed after a method finishes execution. These variables, called static method variables, persist in memory and retain their values through multiple executions of a method. You declare a static variable with the Static keyword as follows:

Visual Basic .NET

Public Sub myMethod() Static Iterations as Integer ' This variable will be incremented every time this method ' is run. Iterations += 1 End Sub 

Although this variable persists in memory, it is still available only during execution of this method. You would use a Static variable for a method that needed to keep track of how many times it had been called.

NOTE
This feature is not available in Visual C#, and the Static keyword in C# has a different meaning, which is discussed in Lesson 5 of this chapter.

Parameters

A method can take one or more parameters. A parameter is an argument that is passed to the method by the method that calls it. Parameters are enclosed in parentheses after the method name in the method declaration, and types must be specified for parameters. Here is an example of a method with parameters:

Visual Basic .NET

Public Sub DisplayName(ByVal name As String, ByVal age As Byte) Console.WriteLine("Hello " & name & ". You are " & _ age.ToString & " years old.") End Sub

Visual C#

public void DisplayName(string name, byte age) { Console.WriteLine("Hello " + name + ". You are " + age.ToString() + "years old."); }

This method requires two parameters: a String parameter, which is given the local name name, and a Byte parameter, which is given the local name age. These variables have scope only for the duration of the method, and they cannot be used after the method returns. For a further discussion of scope, see Lesson 5 of this chapter.

Parameters can be passed in two ways, by value or by reference. In the .NET Framework, parameters are passed by value by default. By value means that whenever a parameter is supplied, a copy of the data contained in the variable is made and passed to the method. Any changes made in the value passed to the method are not reflected in the original variable. Although it is the default setting, you can explicitly indicate that a variable be passed by value in Visual Basic with the ByVal keyword.

When parameters are passed by reference, on the other hand, a reference to the memory location where the variable resides is supplied instead of an actual value. Thus, every time the method performs a manipulation on that variable, the changes are reflected in the actual object. To pass a parameter by reference in Visual Basic .NET, you use the keyword ByRef. In Visual C#, the keyword ref is used. The following example demonstrates passing parameters by value or by reference:

Visual Basic .NET

Public Sub Demo1() Dim x, y As Integer x = 15 y = 20 ' This line calls the Demo2 method (see below) Demo2(x, y) ' What values will x and y have now? MessageBox.Show("X = " & x.ToString & " Y = " & y.ToString) End Sub Public Sub Demo2(ByVal p1 As Integer, ByRef p2 As Integer) p1 = p1 + p2 p2 = p2 + p1 End Sub

Visual C#

public void Demo1() { int x,y; x = 15; y = 20; // This line calls the Demo2 method (see below) Demo2(x, ref y); // What values will x and y have now? System.Windows.Forms.MessageBox.Show("X = " + x.ToString() +  " Y = " + y.ToString()); } public void Demo2(int p1, ref int p2) { p1 = p1 + p2; p2 = p2 + p1; }

In this example, two variables named x and y are created and assigned values. The variables x and y are then passed to the second method. X is passed by value, y is passed by reference, and both are represented in the second method as the variables p1 and p2. Because p1 is passed by value, it represents a copy of the data stored in x, and the manipulations performed on it are for naught. Once the method ends, the variable goes out of scope and its memory is reclaimed. The parameter p2, on the other hand, does not contain a value at all; rather, it contains a reference to the actual data stored in the variable y. Thus, when the line p2 = p2 + p1 is reached, the value stored at the memory location represented by p2 is changed. Therefore, when the final line of the Demo1 method is reached, the value of x will be unchanged at 15, but the value of y will have changed and will be equal to 55.

Note that if your parameter is a reference type, it makes no difference if the parameter is passed by value or by reference the behavior will be the same. In both cases, any manipulations done on the parameter will be reflected in the object passed as a parameter.

Output Parameters

In Visual C#, you can also use output parameters. This feature is not available in Visual Basic .NET. An output parameter is a parameter that is passed from a called method to the method that called it that is, in the reverse direction. Output parameters are useful if you want a method to return more than a single value. An output parameter is specified by using the out keyword. Output parameters are always passed by reference and do not need to be initialized before use. The following example demonstrates output parameters:

Visual C#

public void aWord (out string Word) { Word = "Mambo"; } public void ShowWord() { string Word; aWord(out Word); Console.Writeline("The word of the day is " + Word); }

Here the ShowWord method calls the aWord method with the output parameter Word. The aWord method assigns a value to the output parameter Word, thereby assigning a value to the Word variable.

Optional Parameters

In Visual Basic .NET, you are able to specify optional parameters for your methods. This feature is not available in Visual C#. You specify a parameter as optional using the Optional keyword. Optional parameters must be the last parameters in a method declaration, and you must supply default values for optional parameters. The following example demonstrates the use of optional parameters:

Visual Basic .NET

Public Sub Cook(ByVal time As Integer, Optional ByVal temp As _ Integer = 350) ' Implementation code goes here End Sub 

Constructors and Destructors

The constructor is the first method that is run when an instance of a type is created. In Visual Basic, the constructor is always Sub New. In Visual C#, it is a method with the same name as the class. You use a constructor to initialize class and structure data before use. Constructors can never return a value and can be overridden to provide custom initialization functionality. Chapter 4 discusses how to override methods. A constructor can also contain calls to other methods. An example of a constructor follows:

Visual Basic .NET

Public Class aClass Public Sub New() ' Class initialization code goes here End Sub End Class

Visual C#

public class aClass { public aClass() { // Class initialization code goes here } }

Similarly, a destructor is the last method run by a class. A destructor (known as a finalizer in Visual Basic) contains code to clean up when a class is destroyed. This cleanup might include decrementing counters or releasing resources. A finalizer in Visual Basic .NET is always Sub Finalize(), and a destructor in Visual C# is a method with the same name as the class preceded by a tilde (~). Examples of destructors follow:

Visual Basic .NET

Public Class aClass Protected Overrides Sub Finalize() ' Clean up code goes here End Sub End Class

Visual C#

public class aClass { ~aClass() { // Clean up code goes here } }

NOTE
In Visual Basic, the finalizer must use the Overrides keyword. The meaning and usage of this keyword is discussed in Chapter 4.

Because garbage collection does not occur in any specific order, it is impossible to determine when a class s destructor will be called.

Lesson Summary

  • Methods perform the data manipulation that gives classes and structures their associated behavior. Methods can return a value, but they do not have to. In Visual Basic .NET, methods that return values are called Functions, and non-value-returning methods are called Subs. In Visual C#, if a method doesn t return a value, it has a return type of void. Methods are called by placing the name of the method in the code along with any required parameters.

  • Methods can have parameters, which are values required by the method. Parameters are passed by value by default. You can pass parameters by reference with the ref keyword (Visual C#) or with the ByRef keyword (Visual Basic .NET). For parameters of reference types, the behavior is the same whether passed by value or by reference. Visual C# allows you to specify output parameters from your method. Visual Basic .NET allows you to designate optional parameters.

  • The constructor is the first method called on instantiation of a type. The constructor provides a way to set default values for data or perform other necessary functions before the object is available for use. Destructors are called just before an object is destroyed and can be used to run clean-up code. Since object cleanup is controlled by the common language runtime, you cannot control when a destructor is called.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

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