About
In this code snippet, we will learn about constants in C#.
A constant is a variable that is marked with the const keyword. Such a variable can only have its value set once at compile-time, after that it can’t be changed anymore.
Note: There are also readonly variables, see how they differ from const here.
Let’s have a look at the code below to see how to declare a constant variable.
Code:
using System; namespace constants { class Program { static void Main(string[] args) { int a = 10; //The variable b is a constant and can't be changed after being assigned. const int b = 15; a = 5; //If we try this we will get an exception. //b = 10; Console.WriteLine("a: " + a + " b:" + b); Console.ReadLine(); } } }