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");
             Console.WriteLine(method);
             Console.ReadLine();
         }
     }
 }
image

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...