0

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 ?

1 Answer 1

4

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}\"}}";
Sign up to request clarification or add additional context in comments.

1 Comment

A note about why using double curleys solves the problem might be useful (i.e. that that's the escape sequence, maybe with a link to the docs)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.