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?

4
  • Possible duplicate of String concatenation: concat() vs "+" operator Commented Oct 25, 2018 at 11:22
  • What exactly do you mean by in each case sequence of information can be different? Please give us some examples Commented Oct 25, 2018 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); Commented Feb 14, 2020 at 13:43
  • weblogs.asp.net/bleroy/… Commented Feb 14, 2020 at 13:48

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

In one case mask can be "{date}/{username}" but in other the order may change.
@Piotr In that case your mask will be like "{1:yy}/{0}";, so it doesn't matter.
1

Sure string.Format()

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

or string interpolation

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

2 Comments

I didn't say precisely. Mask is downloaded from db and I should be generated automatically.
What I get from db is whole mask, but i can't use it like this: string result = $"{mask}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.