Skip to content

String extension methods

Alex Kamsteeg edited this page Aug 8, 2015 · 11 revisions

Overview

SwissArmyKnife adds the following extension methods to string:

FormatWith()

The FormatWith() extension method makes formatting strings a more fluent and more natural affair. Normally you would do the following to format a string:

var s = string.Format("Lorem {0} dolor {1} amet", "ipsum", "sit");

This can be a bit tedious and less readable, for example when you use it to format a message for an exception:

if (degreesCelcius < -273.15)
    throw new ArgumentOutOfRangeException(nameof(degreesCelcius), string.Format("The specified temperature is {0} but it cannot be below 0K (-271,15)", degreesCelcius));

Instead of that, you can use the more natural syntax of FormatWith():

var s = "lorem {0} dolor {1} amet".FormatWith("ipsum", "sit");
// or
var s1 = "lorem {0} dolor {1} amet";
s1 = s1.FormatWith("ipsum", "sit");

Or, when throwing exceptions:

if (degreesCelcius < -273.15)
    throw new ArgumentOutOfRangeException(nameof(degreesCelcius), "The specified temperature is {0} but it cannot be below 0K (-271,15)".FormatWith(degreesCelcius));

Clone this wiki locally