Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A string with string interpolation format from database use it in C# code

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. ^-^

like image 685
Jasper Dolorito Layug Avatar asked Mar 10 '26 19:03

Jasper Dolorito Layug


1 Answers

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).

like image 101
Olivier Jacot-Descombes Avatar answered Mar 12 '26 09:03

Olivier Jacot-Descombes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!