C# Constant
In this chapter you will learn:
- What is a constant
- How to create a constant field
- Example for defining a constant field
- Local Constants
Description
A constant is a field whose value can never change.
These variables must be given initial values when they are declared. const implies static.
A constant can be any of the built-in numeric types, bool, char, string, or an enum type.
Syntax
We can create a public constant in the following way:
public class className
{
public const type ConstantName = constant value;
}
Constants can be declared local to a method. For example:
static void Main()
{ /*from w w w .j a v a 2 s .c om*/
const double twoPI = 2 * System.Math.PI;
...
}
Example
A constant is declared with the const keyword and must be initialized with a value. For example:
using System;//from w w w. jav a 2 s .c o m
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.
Example 2
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 w ww .ja v a 2 s.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:
- How to create read only field
- Example for Read only field
- How to set the initial value to a read only field in constructor