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?
Sure string.Format()
string mask = string.Format("{0:yy}/{1}", date, username);
string mask = $"{date:yy}/{username}";
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.