C# Keywords Tutorial Part 17: const

C# Keywords Tutorial Part 17: const

Popular programming language C# offers a number of tools to speed up and improve the development process. The “const” keyword is one such feature that enables programmers to provide a constant value that cannot be changed while the program is being executed. The “const” keyword in C# will be covered in this blog post, along with some code examples that show how to use it.

What does the C# word “const” mean?

When defining a constant value that cannot be altered while the program is running, the “const” keyword is used. A constant value cannot be changed once it has been allocated. Fields or local variables that have a value initialized at the moment of declaration are given the “const” keyword.

Code Examples: Let’s take a look at some code examples to understand how the “const” keyword works in C#.

Example 1: Constant Field In this example, we will declare a constant field that contains a string value. The value of the field cannot be modified at runtime.

class Program
{
    const string GREETING = "Hello, World!";

    static void Main(string[] args)
    {
        Console.WriteLine(GREETING);
    }
}

In this example, we declared a constant field “GREETING” and initialized it with the value “Hello, World!”. We then printed the value of the field using the “Console.WriteLine” method. When we run this program, the output will be “Hello, World!”.

Example 2: Constant Local Variable In this example, we will declare a constant local variable inside a method. The value of the variable cannot be modified at runtime.

class Program
{
    static void Main(string[] args)
    {
        const int MAX_VALUE = 100;
        int num = 50;

        if (num < MAX_VALUE)
        {
            Console.WriteLine("The number is less than the maximum value.");
        }
    }
}

In this example, we declared a constant local variable “MAX_VALUE” inside the “Main” method and initialized it with the value 100. We then declared a non-constant variable “num” and initialized it with the value 50. We used an if statement to check if “num” is less than “MAX_VALUE” and printed a message if it is. Since “MAX_VALUE” is a constant variable, its value cannot be modified at runtime.

Share this post

Leave a Reply

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