Information Technology Reference
In-Depth Information
This code produces the following output:
pi = 3.1416
Unlike actual statics, however, constants do not have their own storage locations, and are
substituted in by the compiler at compile time, in a manner similar to #define values in C and
C++. This is shown in Figure 6-6, which illustrates the preceding code. Hence, although a con-
stant member acts like a static, you cannot declare a constant as static .
static const double PI = 3.14;
Error: can't declare a constant as static
Figure 6-6. Constant fields act like static fields, but do not have a storage location in memory.
Local Constants
A local constant, like a local variable, is declared in a method body or code block, and goes out
of scope at the end of the block in which it is declared. For example, in the following code, local
constant PI goes out of scope at the end of Main .
static void Main()
{
const double PI = 3.1416; // Local constant
for (int radius = 1; radius <= 5; radius++)
{
double area = radius * radius * PI; // Read from local constant
Console.WriteLine
("Radius: {0}, Area: {1}", radius, area);
}
}
Search WWH ::




Custom Search