Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Define Constants in C#

Constants are fields whose values are set at compile time and can never be changed. Use constants to provide meaningful names instead of numeric literals ("magic numbers") for special values.

NoteNote:

In C# the #define preprocessor directive cannot be used to define constants in the way that is typically used in C and C++.

To define constant values of integral types (int, byte, and so on) use an enumerated type. For more information, see enum (C# Reference).

To define non-integral constants, one approach is to group them in a single static class named Constants. This will require that all references to the constants be prefaced with the class name, as shown in the following example.

static class Constants
{
    public const double Pi = 3.14159;
    public const int SpeedOfLight = 300000; // km per sec.

}
class Program
{
    static void Main()
    {
        double radius = 5.3;
        double area = Constants.Pi * (radius * radius);
        int secsFromSun = 149476000 / Constants.SpeedOfLight; // in km
    }
}

The use of the class name qualifier helps ensure that you and others who use the constant understand that it is constant and cannot be modified.

Community Additions

ADD
Show:
© 2015 Microsoft