
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to declare and initialize constant strings in C#?
To set a constant in C#, use the const keyword. Once you have initialized the constant, on changing it will lead to an error.
Let’s declare and initialize a constant string −
const string one= "Amit";
Now you cannot modify the string one because it is set as constant.
Let us see an example wherein we have three constant strings. We cannot modify it after declaring −
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 // one = "David"; Console.WriteLine(two); Console.WriteLine(three); } }
Output
Amit Tom Steve
As shown above, if I will try to modify the value of constant string one, then it will show an error −
// compile-time error // one = "David";
- Related Articles
- What is a string? Declare and initialize the strings in C language
- How to declare and initialize a dictionary in C#?
- How to declare and initialize a list in C#?
- How to initialize and compare strings?
- How to Initialize and Compare Strings in Java?
- How to Initialize and Compare Strings in C#?
- How to declare, create, initialize and access an array in Java?
- How do I declare and initialize an array in Java?
- How do you declare, initialize and access jagged arrays in C#?
- Declare variable as constant in C
- Different ways to declare variable as constant in C and C++
- How to declare and instantiate Delegates in C#?
- How to declare and use Interfaces in C#?
- How to initialize variables in C#?
- How to initialize List in Kotlin?

Advertisements