1

For example I have a string that was retrieved from the database.

string a = "The quick brown {Split[0]}   {Split[1]} the lazy dog";
string b = "jumps over";

And then I will perform this code.

String[] Split= b.Split(' ');
String c= $"{a}";
Console.Writeline(c):

This method is not working. Do you have any idea how can this become possible? I appreciate your help. ^-^

  • Hello. Your question is not very clear. Can you explain little more what exactly you are expecting? What is the result you are getting from your current code? – Arghya C Nov 11 '21 at 18:17
  • 3
    The string interpolation syntax is a compiler thing, there is no way to invoke this at runtime. Your next best thing is to use `string.Format`, but then all the heavy lifting has to be done outside of the string. – Lasse V. Karlsen Nov 11 '21 at 18:21
  • Hello, I appreciate your response. The .Net 6 rc2 shows the value of the "string a" as it is. I mean, it doest change the "{Split[0]}" to jumps for example. – Jasper Dolorito Layug Nov 11 '21 at 18:31

2 Answers2

4

The interpolated strings are interpreted by the compiler. I.e., for example in

string a = "fox";
string b = "jumps over";

// this line ...
string s = $"The quick brown {a} {b} the lazy dog";

... is converted to

string s = String.Format("The quick brown {0} {1} the lazy dog", a, b);

... by the compiler.

Therefore, you cannot use string interpolation at runtime with variable names in a (regular) string.

You must use String.Format at runtime:

string a = "The quick brown {0} {1} the lazy dog";
string b = "fox;jumps over";

string[] split = b.Split(';');
string c = String.Format(a, split[0], split[1]);
Console.Writeline(c):

Note that a runtime, the names of the local variables are not known. If you decompile a compiled C# programm, the decompiled code will contain generic names for local variables like l1, l2 etc. (depending on the decompiler).

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • this is much detailed and should be the answer. +1 – Abhinav Pandey Nov 11 '21 at 18:42
  • 1
    Thank you so much. I found what I'm looking for from your example. Here is my solution.string a = "The quick brown fox {0} {1} the lazy dog"; string b = "jumps over"; string[] split = b.Split(' '); string c = String.Format(a, split); Console.WriteLine(c); – Jasper Dolorito Layug Nov 11 '21 at 19:10
0

As LasseV.Karlsen and Hans Kesting has explained you can use string.Format in this scenario. Let me give you a quick example:

string b = "jumps over";
string[] Split = b.Split(' ');
string c = string.Format("The quick brown fox {0} {1} the lazy dog.",Split[0], Split[1]);
Console.WriteLine(c);

Note that this is just one example with string.Format while there exist countless other uses for the same. Your best resource to learn more about this method could be Microsoft Documentation.