const value
In this chapter you will learn:
Constant value
The const modifier is used to declare fields or local variables that cannot be changed. These variables must be given initial values when they are declared. const implies static.
We can use const modifier to indicate that a field is a constant. The following Math class has a constant field PI.
class Math
{
public const double PI = 3.14;
}
using System;//j a v a 2 s . com
class Constants
{
public const int value1 = 33;
public const string value2 = "Hello";
}
class MainClass
{
public static void Main()
{
Console.WriteLine("{0} {1}",
Constants.value1,
Constants.value2);
}
}
The code above generates the following result.
Local const value
const field can be used in a method.
The following code uses expressions to calculate and display the circumference of a circle.
class MainClass//from j a v a 2s . c o m
{
public static void Main()
{
const double Pi = 3.14159;
double diameter = 2.5;
double circumference = Pi * diameter;
System.Console.WriteLine("Circumference = " + circumference);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class