Clever way to append 's' for plural form in .Net (syntactic sugar)

Viewed 23181

I want to be able to type something like:

Console.WriteLine("You have {0:life/lives} left.", player.Lives);

instead of

Console.WriteLine("You have {0} {1} left.", player.Lives, player.Lives == 1 ? "life" : "lives");

so that for player.Lives == 1 the output would be: You have 1 life left.
for player.Lives != 1 : You have 5 lives left.

or

Console.WriteLine("{0:day[s]} till doomsday.", tillDoomsdayTimeSpan);

Some systems have that built-in. How close can I get to that notation in C#?

EDIT: Yes, I am specifically looking for syntactic sugar, and not a method to determine what singular/plural forms are.

14 Answers

If your application is English on you can use all the solutions shown here. However if you plan to localize the application the plural enabled message must be done in a proper way. This means that you may need multiple patterns (from 1 to 6) depending on the language and the rule to choose what the pattern is used depends on the language.

For example in English you would have two patterns

"You have {0} live left" "You have {0} lives left"

Then you would have a Format function where you pass these two patterns with the liveAmount variable.

Format("You have {0} live left", "You have {0} lives left", liveAmount);

In a real application you would not hard code the string but would use resource strings.

Format would know what the active language is and if English it would use

if (count == 1)
  useSingularPattern
else
  usePluralPattern

To implement this yourself is a bit complex bu you don't have to. You can you an open source project I have made

https://github.com/jaska45/I18N

By using it you can easily get the string

var str = MultiPattern.Format("one;You have {0} live left;other;You have {0} lives left", liveAmount);

That's it. The library knows what pattern to use depending on the passed liveAmount paramter. The rules have been extracted from CLDR into library .cs file.

If you want to localize the application you just put the multi pattern string into .resx and let the translator to translate it. Depending on the target language the multi pattern string might contains 1, 2, 3, 4, 5 or 6 patterns.

Related