Skip to content

Instantly share code, notes, and snippets.

@EgorBron
Last active June 20, 2023 13:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EgorBron/15cb5915722ff971b5d2ce2a36257536 to your computer and use it in GitHub Desktop.
Save EgorBron/15cb5915722ff971b5d2ce2a36257536 to your computer and use it in GitHub Desktop.
Advanced (and better) keyword-based format (with extension methods) for C# (and other .NET languages)
namespace AdvFormat;
/// <summary>
/// Advanced (and better) keyword-based format (with extension methods)
/// </summary>
public static class AdvFormat {
/// <summary>
/// Format string from dict with keywords
/// </summary>
/// <param name="srcStr">Source string (string to format)</param>
/// <param name="format">Dictionary, where keys is keyword for format, and values is values!</param>
/// <param name="strictize">Need to throw exception if formattion failed?</param>
/// <returns>Formatted string</returns>
/// <exception cref="FormatException">When formattion fails</exception>
public static string Format(this string srcStr, IDictionary<string, object> format, bool strict = false) {
if (string.IsNullOrEmpty(srcStr)) throw new FormatException("unable to format empty string");
foreach (var k in format.Keys)
try {
srcStr = srcStr.Replace($"{{{k}}}", format[k].ToString());
} catch (ArgumentNullException e) {
if (strict) throw new FormatException("unable to format string with null key", e);
} catch (ArgumentException e) {
if (strict) throw new FormatException($"unable to format string with {{{k}}} key", e);
}
return srcStr;
}
/// <summary>
/// Classic <see cref="string.Format(string, object?[])"/>
/// </summary>
/// <param name="srcStr">Source string (string to format)</param>
/// <param name="formats">An object array that contains zero or more objects to format</param>
/// <returns>Formatted string</returns>
/// <exception cref="FormatException">When formattion fails</exception>
/// <exception cref="ArgumentNullException">Source string or args is null</exception>
public static string Format(this string srcStr, params object[] formats) {
return string.Format(srcStr, formats);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment