C# const Example: Understanding Constants in the Easy Way
Hey there, fellow coder! 🚀 Ever needed a value in your program that never changes? Something that stays fixed forever? That’s where const
comes in!
In this lesson, you’ll learn:
What You Are Going to Learn in This Lesson
✅ What const
is and why we use it.
✅ A real-world example that makes it super clear.
✅ A complete C# const Example with explanation and output.
✅ When to use const
(and when not to).
Let’s jump right in! 🎉
Introduction to const
in C#
In C#, const
is used to declare constant values—values that never change throughout the program.
Imagine you’re writing a program that calculates the area of a circle. You’ll need π
(pi), which is always 3.14159. Instead of defining it repeatedly, you declare it as a constant:
const double Pi = 3.14159;
Now, Pi
cannot be changed anywhere in the program. If you try, the compiler will throw an error! 🚨
Real-World Scenario: Fuel Price Tracker
Let’s say you’re building a fuel price tracker. The government fixes a tax rate, and it doesn’t change. You can use const
to store this fixed tax percentage.
C# const Example – Fuel Price Calculation
using System;
class Program
{
static void Main()
{
const double TaxRate = 0.18; // 18% tax (fixed)
double fuelPrice = 100.0; // Base price of fuel
double totalPrice = fuelPrice + (fuelPrice * TaxRate);
Console.WriteLine($"Fuel Price (with tax): {totalPrice}");
}
}
Output:
Fuel Price (with tax): 118.0
Explanation:
1️⃣ We declare TaxRate
as const
, meaning it cannot change.
2️⃣ We set fuelPrice
as 100.0.
3️⃣ We calculate the final price, adding an 18% tax.
4️⃣ Finally, we print the total price.
See how const
keeps things clean and error-proof? No accidental changes to tax rates! 🎯
Key Rules for Using const
✔ Must be assigned at the time of declaration.
✔ Can only hold primitive types (int
, double
, string
, etc.).
✔ Cannot be modified later in the program.
✔ Improves code readability and maintainability.
When NOT to Use const
?
🚫 If the value might change in the future, don’t use const
.
🚫 If you need calculated or runtime values, const
won’t work. Use readonly
instead!
Example:
readonly double todayRate = GetCurrentTax(); // ✅ Allowed
const double todayRate = GetCurrentTax(); // ❌ Error! Cannot assign a method result.
Conclusion
You made it! 🎉 Now, you know what const
is and how to use it.
✔ const
helps you store fixed values that never change.
✔ It makes your code clean, readable, and safe from accidental modifications.
✔ Use it when you’re 100% sure the value will never change.
👉 If you have any difficulty or questions, drop a comment. We’ll be happy to help you! 😊
Next What?
Now that you’ve nailed const
, let’s move on to something exciting—the this
statement! In the next lesson, you’ll see how this
helps manage object references in C#. Stay tuned! 🚀