C# Constant

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 ww.  ja  va 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.ja v 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/* w  ww  . ja v a2  s. co 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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor