Dynamic String.Format depending on parameters

We give the following examples:

string amountDisplay = presentation.Amount == 1 ? "" : String.Format("{0} x ", presentation.Amount);

In any case, use String.Format so that it is formatted depending on the properties without having to fulfill the condition of the "value" of the parameters?

another use case:

String.Format("({0}) {1}-{2}", countryCode, areaCode, phonenumber); 

If I have only a phone number, I will get something like "() -5555555", which is undesirable.

another use case:

String.Format("my {0} has {1} cat[s]", "Aunt", 3) 

in this case, I would like to include s in [] if the value is> 1, for example.

Is there any black String.Format syntax that removes parts of the code depending on the value of the parameters or null?

Thank.

+5
source share
4 answers

. [s], , , .

. , areaCode null, , string, . :

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(......);
}

, . , . .

+2

PluralizationServices. - :

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");
+1

:

string str = "my {0} has {1} cat" + ((value > 1) ? "s" : "");

str = String.Format(str, "Aunt", value);
0

, :

int x = 3;
String.Format("my {0} has {1} cat{2}", "Aunt", x, x > 1 ? "s" : ""); 
0

All Articles