-
Notifications
You must be signed in to change notification settings - Fork 0
Using SmartFormat
The simple answer is: call the static function Smart.Format in the SmartFormat namespace.
Smart.Format takes a template and some arguments, and returns the formatted string:
string result = Smart.Format("{Name} {Age}", user);
There are also extension methods that allow an alternative syntax:
string result = "{Name} {Age}".FormatSmart(user);
-
Reflection: Properties, fields, and even parameterless methods can be used as selectors for a placeholder, and selectors can be chained using dot-notation. See Reflection Syntax.
var result = Smart.Format("{User.FirstName.ToLower} {User.LastName.ToUpper}", arg); // result: "scott RIPPEY" -
Conditional Formatting: One option is chosen, depending on the selected value. Options are separated with the pipe
|character. If the value equals 1, the first option is chosen; otherwise the second option is chosen. This works on many types of objects as well, including specific rules forDateTime,Enumvalues, andString. See Conditional Formatting Syntax.var result = Smart.Format("There {0:is|are} {0} {0:item|items}", 1 or 2); // result: "There is 1 item" or "There are 2 items" -
Array Formatting: Uses a template to format each item in the collection, and joins the items together with a separator. You can even use a different separator for the final item. See Array Formatting Syntax.
var result = Smart.Format("{0:N2|, } ... {1:|, |, and }", new []{ 1,2,3 }, new[]{"A","B","C"}); // result: "1, 2, 3 ... A, B, and C"
Internally, the Smart class has a static property Default that contains an instance of SmartFormatter that does the formatting. You can use this Default instance to add plugins and change parsing options, or you can replace it entirely with a new SmartFormatter.
Calling Smart.Format() is merely a shortcut for calling Smart.Default.Format().
You can even avoid using the Smart class altogether. Just create a new SmartFormatter, customize its options, and call Format(...). The system is very flexible.