简体   繁体   中英

What does a '$' string prefix mean when not used for interpolation?

I've just come across this code in an article on .NET Core configuration , and the dictionary keys look very foreign to me:

static IReadOnlyDictionary<string, string> DefaultConfigurationStrings{get;} = new Dictionary<string, string>()
    {
        ["Profile:UserName"] = Environment.UserName,
        [$"AppConfiguration:ConnectionString"] = DefaultConnectionString,
        [$"AppConfiguration:MainWindow:Height"] = "400",
        [$"AppConfiguration:MainWindow:Width"] = "600",
        [$"AppConfiguration:MainWindow:Top"] = "0",
        [$"AppConfiguration:MainWindow:Left"] = "0",
    };

Why the $ and why the [...] ? Something to do with not using comma-separated key-value pairs?

The brackets are the new index initializers . It's just another way to initialize a dictionary that's a bit more readable than the collection initializers that have been there before.

As for the strings, when not using interpolations, it's just a simple string, nothing more. Presumably the compiler won't even generate the string.Format call for such strings. You can remove the $ just as well (it's the same with verbatim string literals when not using any of the different features).

One possible reason for the $"" strings might be, though, that it's a hint to either a source code preprocessor or static analysis tool that the string is somehow special. I've seen something similar used with verbatim string literals to prevent ReSharper from suggesting to translate the string for i18n. That's something you'd look for in your build environment, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM