- Home /
A string converted from Json cant become "smart" and understand variables in my code, true or false?
Hi,
Im having a problem with a string I have converted from Json. I cant find a way to make the string able to understand variables I have in my code. Is it even possible?
void Test()
{
int a = 44;
int b = 55;
string justARegularString = $"Some numbers: {a.ToString()}, {b.ToString()}";
Console.WriteLine(justARegularString); //Output = "Some numbers: 44, 55"
// A string converted from Json can't have the $ prefix. I want to put it there, but How!?
string aStringFromAJsonFile = "Some numbers: {a.ToString()}, {b.ToString()}";
Console.WriteLine(aStringFromAJsonFile); // Output = "Some numbers: {a.ToString()}, {b.ToString()}"
string aFailedAttempt = "$" + aStringFromAJsonFile;
Console.WriteLine(aFailedAttempt);// Output = "$Some numbers: {a.ToString()}, {b.ToString()}"
}
I think there's some confusion here that's making this seem a bit too complicated.
Is there a reason you aren't just using string.Format()?
string justARegularString = string.Format("Some numbers: {0}, {1}", a, b);
Answer by Bunny83 · Oct 11, 2017 at 06:12 PM
No, string interpolation is a C#6 feature which is not available in the version that Unity uses.
Apart from that string interpolation only works on string literals. So dynamic strings are not supported. It's a compiler feature and the string literal is actually replaced by a String.Format call i guess.
edit
Looks like C# 6 support has pretty much arrived. However it doesn't really matter for this question since it only works on string literals. It can't really work on actual string values at runtime. How should it get access to everything that's available in the current scope?