Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
373 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...