static Methods, static Variables and Class Math

Although most methods execute on specific objects in response to method calls, this is not always the case. Sometimes a method performs a task that does not depend on the contents of any object. Such a method applies to the class in which it is declared as a whole and is known as a static method. It is not uncommon for a class to contain a group of static methods to perform common tasks. For example, recall that we used static method Pow of class Math to raise a value to a power in Fig. 6.6. To declare a method as static, place the keyword static before the return type in the method's declaration. You call any static method by specifying the name of the class in which the method is declared, followed by the dot (.) operator and the method name, as in

ClassName.methodName( arguments )

We use various methods of the Math class here to present the concept of static methods. Class Math (from the System namespace) provides a collection of methods that enable you to perform common mathematical calculations. For example, you can calculate the square root of 900.0 with the static method call

Math.Sqrt( 900.0 )

The preceding expression evaluates to 30.0. Method Sqrt takes an argument of type double and returns a result of type double. To output the value of the preceding method call in the console window, you might write the statement

Console.WriteLine( Math.Sqrt( 900.0 ) );

In this statement, the value that Sqrt returns becomes the argument to method WriteLine. Note that we did not create a Math object before calling method Sqrt. Also note that all of Math's methods are statictherefore, each is called by preceding the name of the method with the class name Math and the dot (.) operator. Similarly, Console method WriteLine is a static method of class Console, so we invoke the method by preceding its name with the class name Console and the dot (.) operator.

Method arguments may be constants, variables or expressions. If c = 13.0, d = 3.0 and f = 4.0, then the statement

Console.WriteLine( Math.Sqrt( c + d * f ) );

calculates and prints the square root of 13.0 + 3.0 * 4.0 = 25.0namely, 5.0. Figure 7.2 summarizes several Math class methods. In the figure, x and y are of type double.

Figure 7.2. Math class methods.

Method

Description

Example

Abs( x )

absolute value of x

Abs( 23.7 ) is 23.7

Abs( 0.0 ) is 0.0

Abs( -23.7 ) is 23.7

Ceiling( x )

rounds x to the smallest integer not less than x

Ceiling( 9.2 ) is 10.0

Ceiling( -9.8 ) is -9.0

Cos( x )

trigonometric cosine of x (x in radians)

Cos( 0.0 ) is 1.0

Exp( x )

exponential method ex

Exp( 1.0 ) is 2.71828

Exp( 2.0 ) is 7.38906

Floor( x )

rounds x to the largest integer not greater than x

Floor( 9.2 ) is 9.0

Floor( -9.8 ) is -10.0

Log( x )

natural logarithm of x (base e)

Log( Math.E ) is 1.0

Log( Math.E * Math.E ) is 2.0

Max( x, y )

larger value of x and y

Max( 2.3, 12.7 ) is 12.7

Max( -2.3, -12.7 ) is -2.3

Min( x, y )

smaller value of x and y

Min( 2.3, 12.7 ) is 2.3

Min( -2.3, -12.7 ) is -12.7

Pow( x, y )

x raised to the power y (i.e., xy)

Pow( 2.0, 7.0 ) is 128.0

Pow( 9.0, 0.5 ) is 3.0

Sin( x )

trigonometric sine of x (x in radians)

Sin( 0.0 ) is 0.0

Sqrt( x )

square root of x

Sqrt( 900.0 ) is 30.0

Tan( x )

trigonometric tangent of x (x in radians)

Tan( 0.0 ) is 0.0

Math Class Constants PI and E

Class Math also declares two static variables that represent commonly used mathematical constants: Math.PI and Math.E. The constant Math.PI (3.14159265358979323846) is the ratio of a circle's circumference to its diameter. The constant Math.E (2.7182818284590452354) is the base value for natural logarithms (calculated with static Math method Log). These variables are declared in class Math with the modifiers public and const. Making them public allows other programmers to use these variables in their own classes. Any variable declared with keyword const is a constantits value cannot be changed after the constant is declared. Both PI and E are declared const because their values never change. Also, any constant is implicitly static (so it is a syntax error to declare a constant with keyword static explicitly). Making these constants static allows them to be accessed via the class name Math and the dot (.) operator, just like class Math's methods. Recall from Section 4.5 that when each object of a class maintains its own copy of an attribute, the variable that represents the attribute is also known as an instance variableeach object (instance) of the class has a separate instance of the variable in memory. There are variables for which each object of a class does not have a separate instance of the variable. That is the case with static variables. When objects of a class containing static variables are created, all the objects of that class share one copy of the class's static variables. Together the static variables and instance variables represent the fields of a class. You will learn more about static variables in Section 9.10.

Why Is Method Main Declared static?

Why must Main be declared static? During application startup when no objects of the class have been created, the Main method must be called to begin program execution. The Main method is sometimes called the application's entry point. Declaring Main as static allows the execution environment to invoke Main without creating an instance of the class. Method Main is often declared with the header:

public static void Main( string args[] )

When you execute your application from the command line, you type the application name, as in

ApplicationName argument1 argument2 ...

In the preceding command, argument1 and argument2 are the command-line arguments to the application that specify a list of strings (separated by spaces) the execution environment will pass to the Main method of your application. Such arguments might be used to specify options (e.g., a file name) to run the application. As you will learn in Chapter 8, Arrays, your application can access those command-line arguments and use them to customize the application.

The header of a Main method does not need to appear exactly as we've shown. Applications that do not take command-line arguments may omit the string[] args parameter. The public keyword may also be omitted. In addition, you can declare Main with return type int (instead of void) to enable Main to return an error code with the return statement. A Main method declared with any one of these headers can be used as the application's entry pointbut you can declare only one such Main method in each class.

In earlier chapters, most applications had one class that contained only Main and some examples had a second class that was used by Main to create and manipulate objects. Actually, any class can contain a Main method. In fact, each of our two-class examples could have been implemented as one class. For example, in the application in Fig. 6.9 and Fig. 6.10, method Main (lines 616 of Fig. 6.10) could have been taken as is and placed in class GradeBook (Fig. 6.9). The application results would be identical to those of the two-class version. You can place a Main method in every class you declare. Some programmers take advantage of this to build a small test application into each class they declare. However, if you declare more than one Main method among the classes of your project, you will need to indicate to the IDE which one you would like to be the application's entry point. You can do this by clicking the menu Project > [ProjectName] Properties... (where [ProjectName] is the name of your project) and selecting the class containing the Main method that should be the entry point from the Startup object list box.

Declaring Methods with Multiple Parameters Visual C# 2005 How to Program (2nd Edition)
ISBN: 0131525239
EAN: 2147483647
Year: 2004
Pages: 600

Similar book on Amazon 