Course Content
C# Basics
C# Basics
Declaring Constants
Constants are similar to variables however their value is always set at the declaration time and cannot be changed later.
They are useful in making the code easier to understand by indicating which values do not and are not supposed to be changed throughout the program. Moreover, it minimizes accidental unwanted changes to the data hence reducing bugs in the code.
When declaring a constant we use a similar syntax to variable declaration but we add the keyword const
before it:
main
using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { const int myVar = 10; Console.WriteLine(myVar); } } }
If we try to modify a constant, the compiler will show an error:
main
using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { const int myVar = 10; myVar = 20; // Error: The left-hand side of an assignment must be a variable, property or indexer. } } }
Everything was clear?