ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

FormatSafe

Formats a string safely, without throwing any exceptions. Adds an exception message to the resulting string instead.

Source

using System;

public static class StringExtensions
{
	/// <summary>
	/// Formats the string safely, without throwing any exceptions.
	/// </summary>
	/// <param name="format">The format source string to apply the given arguments to.</param>
	/// <param name="args">Arguments to apply to the format source string.</param>
	/// <returns>The formatted string. Null if the format source string was null.</returns>
	/// <remarks>
	/// Basic Example:
	/// <example><![CDATA[
	/// var message = "Hello, {0}!";
	/// var formattedMessage = message.FormatSafe("World");
	/// // formattedMessage now contains the string "Hello, World!".
	/// ]]></example>
	/// Error Example:
	/// <example><![CDATA[
	/// var message = "Hello, {1}!";
	/// var formattedMessage = message.FormatSafe("World");
	/// // formattedMessage now contains the string "Hello, {0}! (Invalid format or args!)".
	/// ]]></example>
	/// </remarks>
	public static string FormatSafe(this string format, params object[] args)
	{
		const string badFormat = " (Invalid format or args!)";

		if (format != null)
		{
			try { return String.Format(format, args); }
			catch { return format + badFormat; }
		}
		return null;
	}
}

Example

var message = "Hello, {0}!";
var formattedMessage = message.FormatSafe("World");
// formattedMessage now "Hello, World!".

// Error Example:
var message = "Hello, {1}!";
var formattedMessage = message.FormatSafe("World");
// formattedMessage now contains "Hello, {1}! (Invalid format or args!)".

Author: Wayne Bloss

Submitted on: 14 okt. 2010

Language: C#

Type: System.String

Views: 5516