Last active
June 20, 2023 13:03
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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