C#: Escape Curly Braces within Formatted String


Problem

When passing in a formatted string as an argument to a method such as Console.WriteLine, String.Format, etc., curly braces have a special meaning. They are used as a placeholder for a variable. Therefore when you want to add a curly brace within the formatted string, but you don’t want it to be interpreted as a placeholder for a variable, you have a problem.

Solution

The solution for this problem is quick and easy. All you need to do is escape the necessary curly braces by escaping it with yet another curly brace. If you want to escape a leading curly brace, you escape it with another leading curly brace. If you want to escape a trailing curly brace, you escape it with another trailing curly brace.

Leading curly brace: {
Trailing curly brace: }

Examples

Console.WriteLine("Here's a leading curly brace: {{");
Console.WriteLine("Here's a trailing curly brace: }}");
Console.WriteLine("Expected command line format MyApp: {0} {1} {{{2} | {3} | {4}}}", arg1, arg2, arg3A, arg3B, arg3C);
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: