Skip to content

v2 Creating your own extension

axunonb edited this page Feb 6, 2022 · 1 revision

A Hello World Example

Implement IFormatter

public class HelloFormatter : IFormatter
{
	private string[] names = new[] {"hello", "hi"};
	public string[] Names { get { return names; } set { this.names = value; } }

	public bool TryEvaluateFormat(IFormattingInfo formattingInfo)
	{
		var iCanHandleThisInput = formattingInfo.CurrentValue is bool;
		if (!iCanHandleThisInput)
			return false;

		formattingInfo.Write("HELLO ");
		if ((bool) formattingInfo.CurrentValue)
			formattingInfo.Write(formattingInfo.FormatterOptions);
		else
			formattingInfo.Write(formattingInfo.Format.GetLiteralText());

		return true;
	}
}

Example usage:

Smart.Default.AddExtensions(new HelloFormatter());

Smart.Format("{value:hello(world):earth}", new { value = true });
// Outputs: "HELLO world"
Smart.Format("{value:hi(world):earth}", new { value = false });
// Outputs: "HELLO earth"

Terminology

A Format String is the template that defines how the data should be formatted.

Let's analyze the following Format String:

"The user {Name} was born in {Birthday:MMMM}, is {Age:000} {Age:year|years} old, and lives in {Address.City}."

Placeholders are defined by { and }, so this example has 5 placeholders: {Name}, {Birthday:MMMM}, {Age:000}, {Age:year|years}, and {Address.City}.

Literal text is the area in-between placeholders: The user , was born in, , is , , old, and lives in.

Each placeholder starts with a list of Selectors, such as Name and Birthday.
Selectors are separated by a period ., known as an Operator, such as Address.City.
Selectors determine what data will be used in the output.

If the placeholder contains a colon :, the remaining text is known as the Item Format.
For example, MMMM, 000, and year|years are Item Formats.
Note that there is a distinction between the entire Format String and the placeholder's Item Format. The Item Format determines how that data will be formatted. For example, MMMM tells the DateTime to output the name of the Month, like January. 000 tells an integer to use 3 digits. Please see Microsoft's Formatting Types Reference for complete documentation of Item Formats.

Clone this wiki locally