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

 Live Demo

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";

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 20-Jun-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements