C# Constants

C# Constants

If you don't want others (or yourself) to overwrite existing values, you can add the const keyword in front of the variable type.

This will declare the variable as "constant", which means unchangeable and read-only:

Example:

const int myNum = 15;
myNum = 20; // error

The const keyword is useful when you want a variable to always store the same value, so that others (or yourself) won't mess up your code. An example that is often referred to as a constant, is PI (3.14159...).

Note: You cannot declare a constant variable without assigning the value. If you do, an error will occur: A const field requires a value to be provided.

C# Constant Syntax

To define a constant, you use the const keyword with the following syntax:

const type ConstantName = value;

The following are the different ways of declaring and initializing constant variables in the c# programming language:

// Constant variables
const string name = "DANI";
const string location = "US";
const int age = 22;

C# Constant Example

Example of defining and using constant fields in c# programming language with const keyword:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
     
        static void Main(string[] args)
        {
            // Constant variables
            const string name = "DANI";
            const string location = "US";
            const int age = 22;

            Console.WriteLine("Name: {0}", name);
            Console.WriteLine("Location: {0}", location);
            Console.WriteLine("Age: {0}", age);
            Console.ReadLine();
        }
    }
}

Output:

C# Constant Example

C# Constant Features

The following are the important features of a constant variable in the c# programming language:

  • In c#, we can create the constant fields using const keyword.
  • In c#, the constant fields must initialize during the time of declaration.
  • In c#, the constant field values will evaluate during the compile time.
  • Once values are assigned to constant fields, those values must be the same throughout the application.