Events
17 Mar, 9 pm - 21 Mar, 10 am
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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.
Note
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.
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
Console.WriteLine(secsFromSun);
}
}
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.
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Events
17 Mar, 9 pm - 21 Mar, 10 am
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowTraining
Module
Store and retrieve data using literal and variable values in C# - Training
Use data in your applications by creating literal values and variable values of different data types.
Documentation
Constants in C# are compile-time literal values, which do not change once the program is compiled. Only C# built-in types can be constants.
Jump statements - break, continue, return, and goto - C# reference
C# jump statements (break, continue, return, and goto) unconditionally transfer control from the current location to a different statement.
How to override the ToString method - C#
Learn how to override the ToString method in C#. Every class or struct inherits Object and gets ToString, which returns a string representation of that object.