Search code examples
c#stringconstants

Can I initialize a const string from a const char in C#?


I am trying to do the following in a way or another:

const char EscapeChar = '\\';
const string EscapeString = EscapeChar.ToString(); // or ("" + EscapeChar)

This does't compile. Is there another way to make it work?


Solution

  • Starting from .net 6.0, with c# version 10 constant interpolated strings were introduced (https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10#constant-interpolated-strings)

    So from .net 6.0 on you can do this using:

    const string EscapeString = $"{EscapeChar}";