C# Constants
C# Constants
Constants in C# are variables whose value cannot be changed once it is assigned. They are useful for storing fixed values like PI, tax rates, or configuration values.
Declaring Constants
Use the const keyword.
-
const→ keyword -
int→ data type -
MAX_VALUE→ constant name -
100→ value
⚠ Once assigned, the value cannot be modified.
Example
Why Use Constants?
-
Prevent accidental value changes
-
Improve code readability
-
Easier maintenance
-
Faster execution (compile-time constant)
Naming Convention
✔ Use UPPERCASE letters
✔ Use underscore (_) for multiple words
Constants with Different Data Types
Constant vs Variable
| Feature | Constant (const) |
Variable |
|---|---|---|
| Value change | ❌ Not allowed | ✅ Allowed |
| Assignment | Only once | Multiple times |
| Use case | Fixed values | Changing data |
const vs readonly
const
-
Compile-time constant
-
Value must be known at compile time
readonly
-
Runtime constant
-
Value set in constructor
Summary
✔ Constants store fixed values
✔ Use const keyword
✔ Cannot be modified
✔ Follow uppercase naming convention
✔ Use readonly for runtime constants
👉 What would you like next?
-
C# Data Types
-
C# Operators
-
C# Type Casting
-
C# Input
-
C# Control Statements
