- 7.1 Introduction
- 7.2 Packaging Code in C#
- 7.3 static Methods, static Variables and Class Math
- 7.4 Methods with Multiple Parameters
- 7.5 Notes on Using Methods
- 7.6 Argument Promotion and Casting
- 7.7 The .NET Framework Class Library
- 7.8 Case Study: Random-Number Generation
- 7.9 Case Study: A Game of Chance; Introducing Enumerations
- 7.10 Scope of Declarations
- 7.11 Method-Call Stack and Activation Records
- 7.12 Method Overloading
- 7.13 Optional Parameters
- 7.14 Named Parameters
- 7.15 C# 6 Expression-Bodied Methods and Properties
- 7.16 Recursion
- 7.17 Value Types vs. Reference Types
- 7.18 Passing Arguments By Value and By Reference
- 7.19 Wrap-Up
7.3 static Methods, static Variables and Class Math
Although most methods are called to operate on the data of specific objects, this is not always the case. Sometimes a method performs a task that does not depend on the data of any object (other than the method’s arguments). Such a method applies to the class in which it’s declared as a whole and is known as a static method.
It’s common 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 member-access operator (.) and the method name, as in
7.3.1 Math Class Methods
Class Math (from the System namespace) provides a collection of static 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
double value = Math.Sqrt(900.0);
The expression Math.Sqrt(900.0) evaluates to 30.0. Method Sqrt takes an argument of type double and returns a result of type double. The following statement displays in the console window the value of the preceding method call:
Here, the value that Sqrt returns becomes the argument to WriteLine. We did not create a Math object before calling Sqrt, nor did we create a Console object before calling WriteLine. Also, all of Math’s methods are static—therefore, each is called by preceding the name of the method with the class name Math and the member-access 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 displays the square root of 13.0 + 3.0 * 4.0 = 25.0—namely, 5.0. Figure 7.1 summarizes several Math class methods. In the figure, x and y are of type double.
Fig. 7.1 | Math class methods.
7.3.2 Math Class Constants PI and E
Each object of a class maintains its own copy of each of the class’s instance variables. There are also variables for which each object of a class does not need its own separate copy (as you’ll see momentarily). Such variables are declared static and are also known as class variables. When objects of a class containing static variables are created, all the objects of that class share one copy of those variables. Together a class’s static variables and instance variables are known as its fields. You’ll learn more about static fields in Section 10.9.
Class Math also declares two double constants for commonly used mathematical values:
Math.PI (3.1415926535897931) is the ratio of a circle’s circumference to its diameter, and
Math.E (2.7182818284590451) is the base value for natural logarithms (calculated with static Math method Log).
These constants 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. A constant is declared with the keyword const—its value cannot be changed after the constant is declared. Fields declared const are implicitly static, so you can access them via the class name Math and the member-access operator (.), as in Math.PI and Math.E.
7.3.3 Why Is Main Declared static?
Why must Main be declared static? During app startup, when no objects of the class have been created, the Main method must be called to begin program execution. Main is sometimes called the app’s entry point. Declaring Main as static allows the execution environment to invoke Main without creating an instance of the class. Method Main is typically declared with the header:
static void Main()
but also can be declared with the header:
static void Main(string args)
which we’ll discuss and demonstrate in Section 8.12, Shuffling and Dealing Cards. In addition, you can declare Main with return type int (instead of void)—this can be useful if an app is executed by another app and needs to return an indication of success or failure to that other app.
7.3.4 Additional Comments About Main
Most earlier examples have 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 app in Figs. 4.11–4.12, method Main (lines 7–43 of Fig. 4.12) could have been moved into class Account (Fig. 4.11). The app results would have been 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 app into each class they declare. However, if you declare more than one Main method among the classes of your project, you’ll need to indicate to the IDE which one you would like to be the app’s entry point. To do so:
With the project open in Visual Studio, select Project > [ProjectName] Properties... (where [ProjectName] is the name of your project).
Select the class containing the Main method that should be the entry point from the Startup object list box.