Reputation: 19705
Giving the following examples:
string amountDisplay = presentation.Amount == 1 ? "" : String.Format("{0} x ", presentation.Amount);
is there anyway to use String.Format so it formats depending on properties without having to do a condition of the 'value' of the parameters ?
another use case:
String.Format("({0}) {1}-{2}", countryCode, areaCode, phonenumber);
if I only have phonenumber, I would end up with something like "() -5555555" which is not desirable.
another use case :
String.Format("my {0} has {1} cat[s]", "Aunt", 3)
in this case, I would like to include the s in the [] if the value > 1 for example.
Is there any black 'syntax' of String.Format that removes code parts depending on value of parameters or null ?
Thanks.
Upvotes: 5
Views: 2949
Reputation: 2515
You can also try PluralizationServices service. Something like this:
using System.Data.Entity.Design.PluralizationServices;
string str = "my {0} has {1} {3}";
PluralizationService ps = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en-us"));
str = String.Format(str, "Aunt", value, (value > 1) ? ps.Pluralize("cat") : "cat");
Upvotes: 1
Reputation: 4568
Not really. You can hack some things for the plural [s], sure, but it won't be a generic solution to match all your use cases.
You should check the validity of your input regardless. If you're expecting areaCode
to be not null, and it's a nullable type like string
, do some checks at the start of your method. For example:
public string Foo(string countryCode, string areaCode, string phoneNumber)
{
if (string.IsNullOrEmpty(countryCode)) throw new ArgumentNullException("countryCode");
if (string.IsNullOrEmpty(areaCode)) throw new ArgumentNullException("areaCode");
if (string.IsNullOrEmpty(phoneNumber)) throw new ArgumentNullException("phoneNumber");
return string.Format(......);
}
It's not the UI's job to compensate for some validation error on the user's input. If the data is wrong or missing, don't continue. It will only cause you strange bugs and lots of pain down the road.
Upvotes: 2
Reputation: 776
Only addresses the second problem, but:
int x = 3;
String.Format("my {0} has {1} cat{2}", "Aunt", x, x > 1 ? "s" : "");
Upvotes: 0
Reputation: 18064
Try using conditional operator:
string str = "my {0} has {1} cat" + ((value > 1) ? "s" : "");
str = String.Format(str, "Aunt", value);
Upvotes: 0