0

I have a string which I want to insert an other string into. For this I use the method string.Format() but it doesn't work since my basestring include {-signs. As soon as I remove them from my string the code works fine.

 string baseString = "This is my base string and when it includes {-signs it {0}.";
 string insertString = "doesn't work";
 string completeString = string.Format(baseString, insertString);

Does someone have a glue about why it doesn't work?

Markus Safar
  • 6,324
  • 5
  • 28
  • 44

1 Answers1

0

You can use '$' for easy inserts into strings. For example:

string inputString = "test";
string anotherString = "test2";
int? codeExample = null;
string example = $"here I am putting my value: {inputString} and I can do it over and over {anotherString} or with code blocks {codeExample ?? 0}";

//result: here I am putting my value: test and I can do it over and over test2 or with code blocks 0

Reference: Microsoft Language Reference

Jamie Lupton
  • 118
  • 8
  • 1
    I am pretty sure you misunderstood the OPs question. He want's to use a string like _some text with a funny curly bracket here { and a placeholder {0}_ – Markus Safar Oct 30 '18 at 10:37
  • That's no different than `String.Format`, it will fail in the same way if there are angle brackets in the format strings. – Panagiotis Kanavos Oct 30 '18 at 10:37
  • Its not exactly the same. You will get a compiler error if you put { in a $ string and if it is put in at runtime then it handles it gracefully and puts the curly brace into the string. – Jamie Lupton Oct 30 '18 at 10:40