Declaring Constants
Constants are like variables, but their value is set once at the time of declaration and cannot be changed later.
They are helpful in making the code more understandable by clearly indicating which values are fixed and should not change throughout the program. Additionally, using constants helps prevent accidental changes to data, thereby reducing bugs in the code.
To declare a constant, we use a syntax similar to variable declaration, but we add the keyword const
before it:
main.cs
12345678910111213using 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.cs
1234567891011121314using 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. } } }
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Awesome!
Completion rate improved to 1.59
Declaring Constants
Sveip for å vise menyen
Constants are like variables, but their value is set once at the time of declaration and cannot be changed later.
They are helpful in making the code more understandable by clearly indicating which values are fixed and should not change throughout the program. Additionally, using constants helps prevent accidental changes to data, thereby reducing bugs in the code.
To declare a constant, we use a syntax similar to variable declaration, but we add the keyword const
before it:
main.cs
12345678910111213using 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.cs
1234567891011121314using 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. } } }
Takk for tilbakemeldingene dine!