2

When importing a string from XML, I want to interpolate variables. What should I do?

string name = "X";
string str = "name = {name}";
Debug.Log($str); //<-- I FAILED..
Super Jade
  • 5,609
  • 7
  • 39
  • 61
Duck9
  • 31
  • 7
  • 7
    Not possible this way. String interpolation is compiler magic and gets transformed to string.Format in the compiled code. I would go for Regex.Replace (or string.Replace). – Klaus Gütter Dec 16 '18 at 05:53
  • Could you please clarify why the fact you got strings from XML is important and also what exactly does not work when you simply use string interpolation normally `string str=$"name={name}"` ? – Alexei Levenkov Dec 16 '18 at 06:12
  • Take a look at the `FormattableString` class, it might help you do what you want: https://learn.microsoft.com/en-us/dotnet/api/system.formattablestring?view=netframework-4.7.2. And, what does your question have to do with XML? – Flydog57 Dec 16 '18 at 06:47
  • I would advice to look into the xml document reader: https://stackoverflow.com/questions/18442917/using-xmldocument-to-read-xml – Aldert Dec 16 '18 at 07:24
  • you forget to use $ as string str = $"name = {name}"; https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated – Manish Jain Dec 16 '18 at 10:18

1 Answers1

1

You forget to use $ - string interpolation.

string name = "X";
string str = $"name = {name}";
Debug.Log(str); //<-- You succeed.
Manish Jain
  • 1,197
  • 1
  • 11
  • 32
  • if you are using c# console then System.Diagnostics.Debugger.Log(1, "", str); should be there in place of last line – Manish Jain Dec 16 '18 at 10:26