Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create const string from string variable

I want to create const string from another string variable. For example the next two code snippets can't compile

1)

string str = "111";
const string str2 = str;

2)

string str = "111";
const string str2 = new string(str.ToCharArray());

Which results in

Error: The expression being assigned to 'str2' must be constant 

Is there any way to create a const string from string variable ?

like image 245
Dimitar Tsonev Avatar asked Dec 13 '12 14:12

Dimitar Tsonev


2 Answers

In short - no.

The value assigned to a const must be a compile time constant.

You can use readonly instead of const, which will let you change the value of the variable - you will only be able to change the reference in the constructor.

like image 155
Oded Avatar answered Sep 30 '22 02:09

Oded


Nope. Because const variables are works on compile time.

Everybody agree on using readonly;

readonly string t = s + " World";
like image 27
Soner Gönül Avatar answered Sep 30 '22 01:09

Soner Gönül