Avatar ·

How to escape curly braces in .NET format strings (C#)

Hello everyone! I just started learning C# and encountered a problem with string formatting.

\n\n

I need to output a string containing curly braces {}, for example: "Value equals {42}". I'm using the String.Format method or string interpolation, but the compiler or runtime treats the curly braces as part of the substitution syntax.

\n\n

Here's an example of code that doesn't work:

\n
int number = 42;\nstring result = String.Format("Value equals {number}"); // Error: Input string was not in a correct format\nConsole.WriteLine(result);\n
\n\n

Or with interpolation:

\n
int number = 42;\nstring result = $"Value equals {number}"; // Outputs "Value equals 42", but I need "Value equals {42}"\nConsole.WriteLine(res