6

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 ?

3
  • Constant variable has to be fully known during the compilation, so it's not possible. Commented Dec 13, 2012 at 14:16
  • use readonly keyword instead of const Commented Dec 13, 2012 at 14:17
  • In these cases static readonly can help substitute. Commented Dec 13, 2012 at 14:17

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Nope. Because const variables are works on compile time.

Everybody agree on using readonly;

readonly string t = s + " World";

Comments

2

Constants are evaluated at compile time so what you want is not possible. However you can substitute the constants with readonly, for example:

string s = "Hello";
readonly string t = s + " World";

Comments

2

Use readonly keyword.

string str = "111";
readonly string str2 = str.ToCharArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.