1

I'm trying to interpolate a string combined of two strings in C#. I have following code in VS 2015:

DateTime date = DateTime.Now;
string username = "abc";
string mask = "{date:yy}/{username}";

What I want in result is:

18/abc

I know that I can interpolate it like:

mask = $"{date:yy}/{username}"

but mask is also an input. So i need something like:

string result = $"{mask}"

but the result is :

"{date:yy}/{username}"

Mask is actually downloaded from the database and in each case sequence of information can be different. I need to store in db whole mask and only complement it in code. I can't use String.Replace() method like

mask.Replace({date}, date.ToString())

because I need to have possibility to add some formatting like :yy, :yyyy, :dd etc.

Is there any possibility to do this?

Piotr
  • 65
  • 5
  • Possible duplicate of [String concatenation: concat() vs "+" operator](https://stackoverflow.com/questions/47605/string-concatenation-concat-vs-operator) – kgzdev Oct 25 '18 at 11:22
  • What exactly do you mean by `in each case sequence of information can be different`? Please give us some examples – Rui Jarimba Oct 25 '18 at 11:31
  • I think a better way to state your question would be like this: string mask = "{date:yy}/{username}"; .... later .... DateTime date = //something string username = //something string maskWithValues = HowDoIInterpolateThis(mask); – user1529413 Feb 14 '20 at 13:43
  • https://weblogs.asp.net/bleroy/c-6-string-interpolation-is-not-a-templating-engine-and-it-s-not-the-new-string-format – user1529413 Feb 14 '20 at 13:48

2 Answers2

2

You can use string.Format() for that:

string mask = GetMaskFromDB(); //assume it returns "{0}/{1:yy}"
string username = "abc";
DateTime dt = DateTime.Now;

var result = string.Format(mask, username, dt);

Result: "abc/18"

References: DotNetFiddle Example, String.Format Method

SᴇM
  • 7,024
  • 3
  • 24
  • 41
1

Sure string.Format()

string mask = string.Format("{0:yy}/{1}", date, username);

or string interpolation

string mask = $"{date:yy}/{username}";
fubo
  • 44,811
  • 17
  • 103
  • 137
  • I didn't say precisely. Mask is downloaded from db and I should be generated automatically. – Piotr Oct 25 '18 at 11:28
  • What I get from db is whole mask, but i can't use it like this: string result = $"{mask}" – Piotr Oct 25 '18 at 11:28