C# is a variable whose value cannot be changed once it has been assigned. Constants are used when you want to define a value that remains the same throughout the lifetime of the program, providing clarity and reducing the risk of accidental changes to important values.
Characteristic of C# Constant
1. A constant must be assigned a value at the time of declaration.
2. The value of a constant cannot be changed after initialization.
3. Constants are implicitly static, meaning they belong to the type itself rather than to an instance of the class.
Syntax:
const data_type constant_name = value;
Explanation:
1. data_type can be any valid C# data type (e.g., int, double, string, etc.).
2. constant_name is the name of the constant.
3. value is the value assigned to the constant, and it must be a compile-time constant (i.e., a value that can be determined when the program is compiled).
Example:
using System;
class ConstantAppExample
{
// Define constants for configuration
public const string AppName = "MyApplication";
public const double AppVersion = 1.0;
static void Main()
{
// Display application configuration using constants
Console.WriteLine($"Application Name: {AppName}");
Console.WriteLine($"Application Version: {AppVersion}");
}
}
Output:
Application Version: 1
Advantages of Using Constants
1. Code Maintainability: If a value is used repeatedly in multiple places, you can change the constant in one place instead of updating it in multiple locations.
2. Readability: Constants give meaningful names to values. For example, StatusCode.OK is clearer than using the raw integer 200.
3. Compile-time Checking: The compiler checks the value assignment at compile-time, which can reduce errors and unexpected behavior.