Constants and Literals in C# Programming
Introduction
Constants and literals are fundamental concepts in C# programming. Constants represent fixed values that do not change during the program's execution, while literals are the actual values assigned to variables or constants in code.
Constants
Constants in C# are immutable values that are defined at compile-time. They are declared using the const
keyword and must be assigned a value at the time of declaration.
Declaring Constants
The syntax for declaring a constant is:
const data_type constant_name = value;
Example
using System; class Program { static void Main() { const double Pi = 3.14159; const int DaysInWeek = 7; const string Greeting = "Hello, World!"; Console.WriteLine("Value of Pi: " + Pi); Console.WriteLine("Days in a Week: " + DaysInWeek); Console.WriteLine("Greeting: " + Greeting); } }
In this example, the values of Pi
, DaysInWeek
, and Greeting
are fixed and cannot be changed.
Literals
Literals are fixed values assigned directly in the code. They can be of various types, including numeric, character, string, and boolean.
Numeric Literals
Numeric literals represent integer or floating-point numbers.
int integerLiteral = 100; double floatingPointLiteral = 3.14;
Character and String Literals
Character literals are enclosed in single quotes, and string literals are enclosed in double quotes.
char characterLiteral = 'A'; string stringLiteral = "Hello, C#!";
Boolean Literals
Boolean literals are true
and false
.
bool isProgrammingFun = true;
Example
using System; class Program { static void Main() { int integerLiteral = 42; double floatingPointLiteral = 3.14159; char characterLiteral = 'C'; string stringLiteral = "C# Programming"; bool booleanLiteral = true; Console.WriteLine("Integer Literal: " + integerLiteral); Console.WriteLine("Floating Point Literal: " + floatingPointLiteral); Console.WriteLine("Character Literal: " + characterLiteral); Console.WriteLine("String Literal: " + stringLiteral); Console.WriteLine("Boolean Literal: " + booleanLiteral); } }
Conclusion
Constants are used for defining fixed values that cannot change during the execution of the program, while literals are the values assigned to variables and constants in code. Understanding these concepts helps write robust and maintainable C# programs.