Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic String.Format depending of params

Tags:

c#

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.

like image 291
Bart Calixto Avatar asked Oct 22 '22 12:10

Bart Calixto


2 Answers

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.

like image 72
Artless Avatar answered Oct 24 '22 02:10

Artless


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");
like image 30
Firoz Ansari Avatar answered Oct 24 '22 02:10

Firoz Ansari