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.
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.
Additional Comments about Method Main
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 |
Preface
Index
Introduction to Computers, the Internet and Visual C#
Introduction to the Visual C# 2005 Express Edition IDE
Introduction to C# Applications
Introduction to Classes and Objects
Control Statements: Part 1
Control Statements: Part 2
Methods: A Deeper Look
Arrays
Classes and Objects: A Deeper Look
Object-Oriented Programming: Inheritance
Polymorphism, Interfaces & Operator Overloading
Exception Handling
Graphical User Interface Concepts: Part 1
Graphical User Interface Concepts: Part 2
Multithreading
Strings, Characters and Regular Expressions
Graphics and Multimedia
Files and Streams
Extensible Markup Language (XML)
Database, SQL and ADO.NET
ASP.NET 2.0, Web Forms and Web Controls
Web Services
Networking: Streams-Based Sockets and Datagrams
Searching and Sorting
Data Structures
Generics
Collections
Appendix A. Operator Precedence Chart
Appendix B. Number Systems
Appendix C. Using the Visual Studio 2005 Debugger
Appendix D. ASCII Character Set
Appendix E. Unicode®
Appendix F. Introduction to XHTML: Part 1
Appendix G. Introduction to XHTML: Part 2
Appendix H. HTML/XHTML Special Characters
Appendix I. HTML/XHTML Colors
Appendix J. ATM Case Study Code
Appendix K. UML 2: Additional Diagram Types
Appendix L. Simple Types
Index