Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to declare and initialize constant strings in C#?
To declare a constant string in C#, use the const keyword. Constants are immutable values that are set at compile-time and cannot be changed during program execution. Once initialized, attempting to modify a constant will result in a compile-time error.
Syntax
Following is the syntax for declaring and initializing a constant string −
const string constantName = "value";
Constants must be initialized at the time of declaration and the value must be a compile-time constant expression.
Key Rules for Constants
-
Constants must be initialized at declaration − you cannot declare and assign later.
-
The value must be a compile-time constant − literals, null, or expressions of constants.
-
Constants are implicitly static and shared across all instances of the class.
-
Attempting to modify a constant after declaration results in a compile-time error.
Example
using System;
class Demo {
const string one = "Amit";
static void Main() {
// displaying first constant string
Console.WriteLine(one);
const string two = "Tom";
const string three = "Steve";
// compile-time error if uncommented
// one = "David";
Console.WriteLine(two);
Console.WriteLine(three);
}
}
The output of the above code is −
Amit Tom Steve
Constants vs Readonly Variables
| const | readonly |
|---|---|
| Must be initialized at declaration | Can be initialized at declaration or in constructor |
| Value must be compile-time constant | Value can be determined at runtime |
| Implicitly static | Can be instance or static |
| Cannot be modified after declaration | Cannot be modified after initialization |
Using Multiple Constants
using System;
class AppConstants {
public const string APP_NAME = "My Application";
public const string VERSION = "1.0.0";
public const string COMPANY = "Tech Corp";
static void Main() {
Console.WriteLine("Application: " + APP_NAME);
Console.WriteLine("Version: " + VERSION);
Console.WriteLine("Company: " + COMPANY);
// Demonstrating constants are accessible without creating instance
Console.WriteLine("Full Info: " + APP_NAME + " v" + VERSION + " by " + COMPANY);
}
}
The output of the above code is −
Application: My Application Version: 1.0.0 Company: Tech Corp Full Info: My Application v1.0.0 by Tech Corp
Conclusion
Constant strings in C# are declared using the const keyword and must be initialized with compile-time constant values. They are immutable, implicitly static, and provide a way to define unchanging string values that are shared across all instances of a class.
