C# Tips and Tricks #7 – Escaping ‘{‘ in C# String.Format

When you are using the string.format , you would have noticed that it might be challenging to have the flower bracket “{” if you want it be to displayed as a part of the string.

For example , you want to show the full method syntax something like this using the string.format.

string method = String.Format(“{0} {1} SetFirstName(string name) {  }”, “public”, “void”);

When you try to run this to display the full syntax of the method , you will encounter the run time error.

SNAGHTML15bace19In order to fix this and show the { and } within the string.Format , you might want to escape the character and display it. The simple solution will be to use double braces as shown below.

using System;
namespace ConsoleApp1
     class Program
         static void Main(string[] args)

            string method = String.Format("{0} {1} SetFirstName(string name) {{  }}", "public", "void");
Copy link
Powered by Social Snap