What are the Constants in C# ???
A Constants in C# is a value that cannot be changed after its declaration. Constants are defined using the “const
” keyword and must be initialized at the time of declaration.
Syntax
const dataType constantName = value;
Example
using System; namespace ConstantExample { class Program { const int MaxValue = 100; const double Pi = 3.14159; const string WelcomeMessage = "Hello, World!"; static void Main(string[] args) { Console.WriteLine("Max Value: " + MaxValue); Console.WriteLine("Pi: " + Pi); Console.WriteLine(WelcomeMessage); } } }
Line-by-Line Notes
const int MaxValue = 100;
- Declares a constant integer named
MaxValue
and initializes it with the value100
. const
: Keyword to declare a constant.int
: Data type for a 32-bit signed integer.MaxValue
: Name of the constant.100
: Initial and unchangeable value assigned toMaxValue
.
const double Pi = 3.14159;
- Declares a constant double-precision floating-point number named
Pi
and initializes it with the value3.14159
. double
: Data type for double-precision floating-point numbers.Pi
: Name of the constant.3.14159
: Initial and unchangeable value assigned toPi
.
const string WelcomeMessage = "Hello, World!";
- Declares a constant string named
WelcomeMessage
and initializes it with the value"Hello, World!"
. string
: Data type for a sequence of characters.WelcomeMessage
: Name of the constant."Hello, World!"
: Initial and unchangeable value assigned toWelcomeMessage
.