C# Constants

C# Code Snippets_ Constants
Share:

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();
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger