StringBuilderInvariantExtensions

Namespace: System.Text · class

Extension methods for StringBuilder which format interpolated strings with InvariantCulture, without having to pass the provider on each call.

Remarks

Replaces the pattern sb.Append(CultureInfo.InvariantCulture, \("...") (verbose, false positives CA1305 when all the holes are strings) with sb.AppendInvariant(\)"..."). The values are written directly in the internal buffer of the (no intermediate string allocation), via the machinery of the BCL, by forcing the invariant culture in the handler's constructor.

Methods

AppendInvariant

static StringBuilder AppendInvariant(StringBuilder sb, ref InvariantAppendInterpolatedStringHandler handler)

Appends an interpolated string formatted with InvariantCulture.

Allows avoiding having to specify CultureInfo.InvariantCulture systematically when calling :

// This method uses the invariant culture, and does not generate false positives for CA1305
sb.AppendInvariant($"hello {name}, temperature is {temperature:D01}°C and current date is {DateTime.Now:yyyy-MM-dd}.")

AppendLineInvariant

static StringBuilder AppendLineInvariant(StringBuilder sb, ref InvariantAppendInterpolatedStringHandler handler)

Appends an interpolated string formatted with InvariantCulture, followed by a line terminator.

Avoids having to specify CultureInfo.InvariantCulture systematically when calling :

// This method uses the invariant culture, and does not generate false positives for CA1305
sb.AppendLineInvariant($"hello {name}, temperature is {temperature:D01}°C and current date is {DateTime.Now:yyyy-MM-dd}.")