Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does interpolating a const string result in a compiler error?

Why does string interpolation in c# does not work with const strings? For example:

private const string WEB_API_ROOT = "/private/WebApi/"; private const string WEB_API_PROJECT = $"{WEB_API_ROOT}project.json"; 

From my point of view, everything is known at compile time. Or is that a feature that will be added later?

Compiler message:

The expression being assigned to 'DynamicWebApiBuilder.WEB_API_PROJECT' must be constant.

Thanks a lot!

like image 490
BendEg Avatar asked Sep 12 '16 13:09

BendEg


People also ask

Can I use string interpolation?

Beginning with C# 10, you can use string interpolation to initialize a constant string. All expressions used for placeholders must be constant strings. In other words, every interpolation expression must be a string, and it must be a compile time constant.

Which strings do interpolate variables?

String interpolation is common in many programming languages which make heavy use of string representations of data, such as Apache Groovy, Julia, Kotlin, Perl, PHP, Python, Ruby, Scala, Swift, Tcl and most Unix shells.


2 Answers

Interpolated strings are simply converted to calls to string.Format. So your above line actually reads

private const string WEB_API_PROJECT = string.Format("{0}project.json", WEB_API_ROOT); 

And this is not compile time constant as a method call is included.


On the other hand, string concatenation (of simple, constant string literals) can be done by the compiler, so this will work:

private const string WEB_API_ROOT = "/private/WebApi/"; private const string WEB_API_PROJECT = WEB_API_ROOT + "project.json"; 

or switch from const to static readonly:

private static readonly string WEB_API_PROJECT = $"{WEB_API_ROOT}project.json"; 

so the string is initialized (and string.Format called) at the first access to any member of the declaring type.

like image 173
René Vogt Avatar answered Oct 02 '22 12:10

René Vogt


An additional explanation why string interpolation expressions are not considered constants is that they are not constant, even if all their inputs are constants. Specifically, they vary based on the current culture. Try executing the following code:

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;  Console.WriteLine($"{3.14}");  CultureInfo.CurrentCulture = new CultureInfo("cs-CZ");  Console.WriteLine($"{3.14}"); 

Its output is:

3.14 3,14 

Note that the output is different, even though the string interpolation expression is the same in both cases. So, with const string pi = $"{3.14}", it wouldn't be clear what code should the compiler generate.

UPDATE: In C# 10/.Net 6, string interpolations that only contains const strings can be const. So the code in the question is not an error anymore.

like image 28
svick Avatar answered Oct 02 '22 12:10

svick