C# Constants


This entry is part 6 of 8 in the series C# Classes Intermediate

A local constant is much like a local variable, except that once it is initialized, its value can’t be changed. Like a local variable, a local constant must be declared inside a block. A constant must be initialized at its declaration. A constant cannot be changed after its declaration.

A local constant, like a local variable, is declared in a method body or code block, and it goes out of scope at the end of the block in which it is declared.

The syntax for declaring a constant is as follows. const is a keyword. The keyword const is not a modifier but part of the core declaration. It must be placed immediately before the type. The Value is the initializer and it is required.

const Type Identifier = Value;

Member constants are like the local constants except that they’re declared in the class declaration rather than in a method. Like local constants, the value used to initialize a member constant must be computable at compile time and is usually one of the predefined simple types or an expression composed of them. Below is an example.

In C# there are no global constants, unlike C and C++.

Constants are like Statics

Member constants act like static values. They’re “visible” to every instance of the class, and they’re available even if there are no instances of the class. Unlike actual statics, 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++.

The following code declares a class called MyConstants with a constant field myInt. Main doesn’t create any instances of MyConstants, and yet it can use field myInt and print its value in the first line of code in Main.

using System;
namespace ConstantsIllustrated
{
    public class MyConstants
    {   // no storage location (compiler substitution)
        public const int myInt = 100;
        public const int yourInt = 2 * myInt;
        public const double PI = 3.1416;
    }
    public static class MyGlobalConstants
    {   // has a storage location
        public static int myInt = 100;
        public static int yourInt = 2 * myInt;
        public static double PI = 3.141593;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(MyConstants.myInt); 
            Console.WriteLine(MyGlobalConstants.yourInt);
        }
    }
}

In the class MyGlobalConstants we must declare each field as public otherwise it will be inaccessible in Main.

Series Navigation<< C# Static MethodsC# Static Class >>