Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to treat a string variable as interpolated string?

Tags:

string

c#

format

the interpolated string is easy, just a string lead with $ sign. But what if the string template is coming from outside of your code. For example assume you have a XML file containing following line:

<filePath from="C:\data\settle{date}.csv" to="D:\data\settle{date}.csv"/>

Then you can use LINQ to XML read the content of the attributes in.

//assume the ele is the node <filePath></filePath>
string pathFrom = ele.Attribute("from").value;
string pathTo = ele.Attibute("to").value;
string date = DateTime.Today.ToString("MMddyyyy");

Now how can I inject the date into the pathFrom variable and pathTo variable?


If I have the control of the string itself, things are easy. I can just do var xxx=$"C:\data\settle{date}.csv";But now, what I have is only the variable that I know contains the placeholder date

like image 327
Gen.L Avatar asked Sep 20 '25 11:09

Gen.L


2 Answers

String interpolation is a compiler feature, so it cannot be used at runtime. This should be clear from the fact that the names of the variables in the scope will in general not be availabe at runtime.

So you will have to roll your own replacement mechanism. It depends on your exact requirements what is best here.

If you only have one (or very few replacements), just do

output = input.Replace("{date}", date);

If the possible replacements are a long list, it might be better to use

output = Regex.Replace(input, @"\{\w+?\}", 
    match => GetValue(match.Value));

with

string GetValue(string variable)
{
    switch (variable)
    {
    case "{date}":
        return DateTime.Today.ToString("MMddyyyy");
    default:
        return "";
    }
}

If you can get an IDictionary<string, string> mapping variable names to values you may simplify this to

output = Regex.Replace(input, @"\{\w+?\}", 
    match => replacements[match.Value.Substring(1, match.Value.Length-2)]);
like image 139
Klaus Gütter Avatar answered Sep 23 '25 00:09

Klaus Gütter


You can't directly; the compiler turns your:

string world = "world";
var hw = $"Hello {world}"

Into something like:

string world = "world";
var hw = string.Format("Hello {0}", world);

(It chooses concat, format or formattablestring depending on the situation)


You could engage in a similar process yourself, by replacing "{date" with "{0" and putting the date as the second argument to a string format, etc.

like image 22
Caius Jard Avatar answered Sep 23 '25 01:09

Caius Jard