C# Constants - Complete Guide
Introduction to Constants
Constants in C# are immutable values known at compile time that remain the same throughout the lifetime of a program. They are declared using the const keyword.
Constants must be assigned when declared and cannot be reassigned later. They are useful for values that never change, such as mathematical constants, configuration values, or other fixed data.
Declaring and Using Constants
Constants are declared with the const keyword and must be initialized immediately:
Example
using System;
namespace ConstantExamples
{
class Program
{
// Class-level constants
public const double PI = 3.14159;
public const int MAX_USERS = 100;
public const string APPLICATION_NAME = "My C# App";
static void Main(string[] args)
{
// Method-level constants
const int MIN_AGE = 18;
const string GREETING = "Welcome to ";
const double TAX_RATE = 0.08;
// Using constants
Console.WriteLine(GREETING + APPLICATION_NAME);
Console.WriteLine("PI value: " + PI);
Console.WriteLine("Minimum age: " + MIN_AGE);
Console.WriteLine("Tax rate: " + TAX_RATE);
// Calculate circle area using constant
double radius = 5.0;
double area = PI * radius * radius;
Console.WriteLine("Area of circle with radius " + radius + ": " + area);
// Constants cannot be reassigned
// PI = 3.14; // Error
// MIN_AGE = 21; // Error
}
}
}
Output
Welcome to My C# App PI value: 3.14159 Minimum age: 18 Tax rate: 0.08 Area of circle with radius 5: 78.53975
Constants vs Readonly Fields
C# provides two ways to create immutable values: const and readonly. Understanding the difference is important:
Example
using System;
namespace ConstVsReadonly
{
class Program
{
// const - compile-time constant, must be initialized at declaration
public const double PI = 3.14159;
// readonly - runtime constant, can be initialized in constructor
public readonly string DatabaseConnectionString;
public readonly DateTime CreatedDate;
public Program()
{
DatabaseConnectionString = "Server=localhost;Database=MyDB;";
CreatedDate = DateTime.Now;
}
static void Main(string[] args)
{
Program program = new Program();
Console.WriteLine("PI: " + PI);
Console.WriteLine("Connection: " + program.DatabaseConnectionString);
Console.WriteLine("Created: " + program.CreatedDate);
// Key differences:
// - const values are resolved at compile time
// - readonly values are resolved at runtime
// - const is limited to primitive types and strings
// - readonly can be any type
// - const members are implicitly static
// - readonly fields are instance-specific unless declared static
}
}
}
Output
PI: 3.14159 Connection: Server=localhost;Database=MyDB; Created: 10/15/2023 2:30:45 PM