Skip to content

String extension methods

Alex Kamsteeg edited this page Aug 14, 2017 · 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));

Truncate()

The Truncate() extension method is a shorthand for the SubString() method. With SubString() you have to write a verbose command:

var s = "lorem ipsum dolor sit amet";

var sTruncated = s.SubString(0, 5); // "lorem"

This is especially true when you want to append a suffix:

var s = "lorem ipsum dolor sit amet";

var sTruncated = s.SubString(0, 5) + "..."; // or String.Format()

With Truncate() the call in both situations gets shorter:

var s = "lorem ipsum dolor sit amet";

var sTruncated = s.Truncate(5); // lorem

// Or with suffix:

var sTruncated = s.Truncate(5, "..."); // "lorem..."

IsNullOrEmpty()

With IsNullOrEmpty() extension method, code like string.IsNullOrEmpty(string) are replaced by "lorem ipsum".IsNullOrEmpty().

string s = null;
var result = s.IsNullOrEmpty(); // True

// Empty string
string s = string.Empty;
var result = s.IsNullOrEmpty(); // True

// Not-empty string
string s = "lorem ipsum";
var result = s.IsNullOrEmpty(); // false

IsNullOrWhiteSpace()

Code like string.IsNullOrWhiteSpace(string) can be replaced by "lorem ipsum".IsNullOrWhiteSpace().

string s = null;
var result = s.IsNullOrWhiteSpace(); // True

// Empty string
string s = string.Empty;
var result = s.IsNullOrWhiteSpace(); // True

// Whitespace string
string s = " ";
var result = s.IsNullOrWhiteSpace(); // True

// Not-empty string
string s = "lorem ipsum";
var result = s.IsNullOrEmpty(); // false

Contains()

An override to the built-in string.Contains(string) method for case-(in)sensitive checking if the value is present in the source.

var s = "Lorem Ipsum";

s.Contains("ipsum", StringComparison.InvariantCultureIgnoreCase); // True

s.Contains("ipsum", StringComparison.InvariantCulture); // False

Clone this wiki locally