FormatString 1.1.0

dotnet add package FormatString --version 1.1.0
                    
NuGet\Install-Package FormatString -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="FormatString" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="FormatString" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="FormatString" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add FormatString --version 1.1.0
                    
#r "nuget: FormatString, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package FormatString@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=FormatString&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=FormatString&version=1.1.0
                    
Install as a Cake Tool

Format String

A simple string template formatting library.

This remedies the ugly coding practices of string concatenation like the one below.

string mode   = "https";
string domain = "frostbane.dev";
string query  = "ak";
int    limit  = 18;

string url = mode + "://" + domain + "?q=" + query + "&n=" + limit.ToString();
// https://frostbane.dev?q=ak&n=18

This can get really ugly when the number of variables increases.

C# has the string interpolation feature but it requires having the values be on the local scope.

string mode   = "https";
string domain = "frostbane.dev";
string query  = "ak";
int    limit  = 18;

string url = $"{mode}://{domain}?q={query}&n={limit}";
// https://frostbane.dev?q=ak&n=18

String interpolation works fine, but it pollutes the scope with local variables.

Usage

adding to dependencies

PS> donet add package formatstring

namespace

using Dev.Frostbane;

Formatting using maps

FormatString sf = new ();

var map = new Hashtable
{
    { "limit", 18 },
    { "query", "ak" },
    { "domain", "frostbane.dev" },
    { "mode", "https" },
};

string template = "{{mode}}://{{domain}}?q={{query}}&n={{limit}}";
string url      = sf.Format(template, map);
// https://frostbane.dev?q=ak&n=18

Formatting using iterables

FormatString sf = new ();

var list = new List<string>()
{
    "frostbane.dev",
    "https",
    "18",
    "ak",
};

string template = "{{1}}://{{0}}?q={{3}}&n={{2}}";
string url      = sf.Format(template, list);
// https://frostbane.dev?q=ak&n=18

Formatting using objects

Given a class, struct, record or whatever object you have.

public class UrlBase
{
    public string mode;
    public static string domain = "frostbane.dev";
}

public class UrlInfo : UrlBase
{
    public string query;
    public int limit;
}

Replacement will occur based on the fields of that object.

FormatString sf  = new ();

UrlInfo urlInfo = new ()
{
    mode  = "https",
    query = "ak",
    limit = 18,
};

string template = "{{mode}}://{{domain}}?q={{query}}&n={{limit}}";
string url      = sf.Format(template, urlInfo);
// https://frostbane.dev?q=ak&n=18

The field search will traverse the object's heirarchy until it finds a public field that matches the key.

Other examples

Check the test folder for more examples.

Internals

Replacement can either be a map (Hashtable or Dictionary<string, object>), an iterable (List<object>, object[], etc.) or any object with public fields.

Matches are replaced with the keys of the map, indexes of an iterable, or fields of the object.

using dictionaries

Due to the noncovariant nature of Dictionaries, only Dictionary<string, object> is allowed. passing a Dictionary<string, string> to format will cause an error.

no matching keys

Any match that has no equivalent key will be ignored.

In the example below, the template has a matcher {{limit}} but the map has no key named limit. The formatter will just ignore the match (since there was no match).

FormatString sf = new ();

var map = new Hashtable
{
    { "query", "ak" },
    { "domain", "frostbane.dev" },
    { "mode", "https" },
};

string template = "{{mode}}://{{domain}}?q={{query}}&n={{limit}}";
string url      = sf.Format(template, map);
// https://frostbane.dev?q=ak&n={{limit}}

There is no null pointer exception if the index does not exist.

FormatString sf = new ();

var arr = new string[]
{
    "frostbane.dev",
    "https",
};

string template = "{{1}}://{{0}}?q={{3}}&n={{2}}";
string url      = sf.Format(template, arr);
// https://frostbane.dev?q={{3}}&n={{2}}

matcher names

  1. Matchers can have any number of spaces inside (and is recommended for clarity). The template below will be parsed similarly with the examples provided.

    string template = "{{ mode }}://{{domain }}?q={{ query}}&n={{    limit }}";
    
  2. Matchers cannot have spaces. Use underscores _ instead of spaces.

  3. Matchers are case sensitive.

    {{DOMAINNAME}} is different from {{domainname}}.

  4. Matchers are typed as string and numeric keys are not converted. Padded zeroes will be as is.

    {{0}} is different from {{00}}.

  5. The keys can be any object, ToString is applied on the object to get the key used for matching.

    • null is rendered as Null.

spaces in key names

Spaces in key names will be replaced by a underscore _ because spaces are not allowed in matchers.

The example below shows an example of a map having keys with spaces.

FormatString sf = new ();

var map = new Hashtable
{
    { "query string", "ak" },
    { "domain name", "frostbane.dev" },
    { "mode", "https" },
    { "result limit", 18}
};

string template = "{{mode}}://{{domain_name}}?q={{query_string}}&n={{result_limit}}";
string url      = sf.Format(template, map);
// https://frostbane.dev?q=ak&n=18

Escaping

Escaping matchers is done by wrapping the match tokens {{, }} with // and // e.g. //{{key}}//. The example below escapes the {{query}} matcher and renders it as is.

FormatString sf = new ();

var map = new Hashtable
{
    { "query", "ak" },
    { "limit", 18 },
    { "domain", "frostbane.dev" },
    { "mode", "https" },
};

string template = "{{mode}}://{{domain}}?q=//{{query}}//&n={{limit}}";
string url      = sf.Format(template, map);
// https://frostbane.dev?q={{query}}&n=18

Escaping the escape sequence is done by doubling the sequence e.g. ////{{key}}////. The example below escapes the //{{query}}// escaped matcher and renders it as is.

FormatString sf = new ();

var map = new Hashtable
{
    { "query", "ak" },
    { "limit", 18 },
    { "domain", "frostbane.dev" },
    { "mode", "https" },
};

string template = "{{mode}}://{{domain}}?q=////{{query}}////&n={{limit}}";
string url      = sf.Format(template, map);
// https://frostbane.dev?q=//{{query}}//&n=18

Configuration

changing the match tokens

Match and escape tokens can be changed according to your team's specifications.

For example, changing the default {{ and }} with { and }.

FormatString sf = new ();

sf.SetMatchTokens("{", "}");

Dictionary<string, object> urlInfo = getUrlInfo();

string template = "{mode}://{domain}?q={query}&n={limit}";
string url      = sf.Format(template, urlInfo);
// https://frostbane.dev?q=ak&n=18

Or changing it with [ and ], which feels natural for iterables.

FormatString sf = new ();

sf.SetMatchTokens("[", "]");

List<string> list = getUrlInfos();

string template = "[1]://[0]?q=[3]&n=[2]";
string url      = sf.Format(template, list);
// https://frostbane.dev?q=ak&n=18

Using only the opening token is possible but not advised. Rigorous testing was not done with only one token, and it will not be a planned feature. The template becomes less readable and is prone to possible bugs.

FormatString sf = new ();

sf.SetMatchTokens("$", string.Empty);

Dictionary<string, object> urlInfo = getUrlInfo();

string template = "$mode://$domain!?q=$query&n=$limit";
string url      = sf.Format(template, urlInfo);

Assert.Equivalent("https://frostbane.dev?q=ak&n=18", url, strict: true);

changing the escape tokens

The default excape tokens // and // can also be changed.

The example below changes both the match and escape tokens.

FormatString sf = new ();

sf.SetMatchTokens("{", "}")
  .SetEscapeTokens("!", "!");

Dictionary<string, object> urlInfo = getUrlInfo();

string template = "{mode}://!{domain}!?q={query}&n={limit}";
string url      = sf.Format(template, urlInfo);
// https://frostbane.dev?q={query}&n=18

Just like the match tokens, you can also configure it to use only opening escape tokens, but it was also not rigorously tested and is not advised.

FormatString sf = new ();

sf.SetMatchTokens("<", ">")
  .SetEscapeTokens("!", string.Empty);

Dictionary<string, object> urlInfo = getUrlInfo();

string template = "<mode>://!<domain>?q=<query>&n=<limit>";
string url      = sf.Format(template, urlInfo);

Assert.Equivalent("https://<domain>?q=ak&n=18", url, strict: true);

Idea behind

This library is a simple port of the javascript micro-format library I made dozens of years ago, which was also made out of necessity because of the ugly string concatenation.

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net6.0

    • No dependencies.
  • net7.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 286 11/2/2023
1.0.0 133 11/1/2023