C# Constant

C# is a variable whose value cannot be changed once it has been assigned. Constants are used when you want to define a value that remains the same throughout the lifetime of the program, providing clarity and reducing the risk of accidental changes to important values.

Characteristic of C# Constant

1. A constant must be assigned a value at the time of declaration.

2. The value of a constant cannot be changed after initialization.

3. Constants are implicitly static, meaning they belong to the type itself rather than to an instance of the class.

Syntax:


const data_type constant_name = value;

Explanation:

1. data_type can be any valid C# data type (e.g., int, double, string, etc.).

2. constant_name is the name of the constant.

3. value is the value assigned to the constant, and it must be a compile-time constant (i.e., a value that can be determined when the program is compiled).

Example:


using System;

class ConstantAppExample
{
    // Define constants for configuration
    public const string AppName = "MyApplication";
    public const double AppVersion = 1.0;

    static void Main()
    {
        // Display application configuration using constants
        Console.WriteLine($"Application Name: {AppName}");
        Console.WriteLine($"Application Version: {AppVersion}");
    }
}

Output:

Application Name: MyApplication
Application Version: 1

Advantages of Using Constants

1. Code Maintainability: If a value is used repeatedly in multiple places, you can change the constant in one place instead of updating it in multiple locations.

2. Readability: Constants give meaningful names to values. For example, StatusCode.OK is clearer than using the raw integer 200.

3. Compile-time Checking: The compiler checks the value assignment at compile-time, which can reduce errors and unexpected behavior.

C# Constant – Interview Questions

Q 1: What is a constant?

Ans: A constant is a fixed value that cannot be changed.

Q 2: Which keyword is used to define constants?

Ans: const

Q 3: Can constants be changed at runtime?

Ans: No, constants cannot be changed.

Q 4: When should we use constants?

Ans: When values remain fixed throughout the program.

Q 5: Can constants be declared inside methods?

Ans: Yes.

C# Constant – Objective Questions (MCQs)

Q1. Which keyword is used to declare a constant in C#?






Q2. When must the value of a const variable be assigned in C#?






Q3. Which of the following statements about constants in C# is true?






Q4. Which data type is used to store true or false values in C#?






Q5. Which of the following is a valid constant declaration in C#?






Related C# Constant Topics