Search code examples
c#string.format

Formatting string - input string was not in correct format


I would like to have a function to receive a string and format it to another string of the following format in C#: (testing is an input variable)

output:
@"{MyKey=testing}"

My simple program is below:

class Program
{
    static void Main(string[] args)
    {
        string s = test("testing");
    }
    private static string test(string myKey)
    {
        string s = string.Format("@{\"MyKey={0}\"}", myKey);
        return s;
    }
}

There is no syntax error but I got this runtime error:

enter image description here

I know the string include special character but I wonder if it is possible to use string.Format to create the output I desire? How should I properly format the string ?


Solution

  • You need to escape those curly braces that should be a part of the string, by using double curly braces. See more here.

    class Program
    {
        static void Main(string[] args)
        {
            string s = test("testing");
            s.Dump();
        }
        private static string test(string myKey)
        {
            string s = string.Format("@{{\"MyKey={0}\"}}", myKey);
            return s;
        }
    }
    

    You can also use string interpolation like this:

    string s = $"@{{\"MyKey={myKey}\"}}";