Skip to content

Instantly share code, notes, and snippets.

@wcoder
Created August 5, 2021 13:34
Show Gist options
  • Save wcoder/de8bf313420c5921094c7e40050c6502 to your computer and use it in GitHub Desktop.
Save wcoder/de8bf313420c5921094c7e40050c6502 to your computer and use it in GitHub Desktop.
The example demonstrates the use of square brackets to extend the C # string.Format ()
using System;
public static class StringExtensions
{
public static string Format(this string str, params object[] parameters)
{
return string.Format(str, parameters);
}
public static string FormatExt(this string str, params object[] parameters)
{
var result = System.Text.RegularExpressions.Regex.Replace(
str,
@"\[(\d+)\]",
m => parameters[int.Parse(m.Groups[1].Value)].ToString());
return result;
}
}
// Example:
class Program
{
static void Main()
{
var result = "my [1] name: {0}, my profile [0] link"
.Format("Qwerty")
.FormatExt("test", "new value");
Console.WriteLine(result);
}
}
@wcoder
Copy link
Author

wcoder commented Aug 5, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment