Last active
May 3, 2018 10:50
-
-
Save waf/411dbb6bdfebdec8fe5f98149c03dcfc to your computer and use it in GitHub Desktop.
Fun with string interpolation
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
using System; | |
using System.Linq; | |
using System.Runtime.CompilerServices; | |
namespace Scratch | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// some miscellaneous variables to interpolate. It is a requirement that the | |
// booleans values must be lowercased, but the non-boolean values should remain as is. | |
bool isCool = true; | |
bool isMagic = true; | |
string uppercase = "HELLO"; | |
// interpolate and implicitly convert to string (what normally happens) | |
string badString = $"http://www.example.com/?isCool={isCool}&isMagic={isMagic}&uppercase={uppercase}"; | |
// interpolate, but pass to function which will do some stuff before explicitly converting to a string | |
string goodString = LowercaseBooleans($"http://www.example.com/?isCool={isCool}&isMagic={isMagic}&uppercase={uppercase}"); | |
Console.WriteLine($"badString: {badString}"); // prints badString: http://www.example.com/?isCool=True&isMagic=True&uppercase=HELLO | |
Console.WriteLine($"goodString: {goodString}"); // prints goodString: http://www.example.com/?isCool=true&isMagic=true&uppercase=HELLO | |
Console.ReadKey(); | |
} | |
static string LowercaseBooleans(FormattableString str) | |
{ | |
// for boolean arguments, lowercase them. | |
var args = str.GetArguments() | |
.Select(arg => | |
arg is bool booleanArg | |
? (booleanArg ? "true" : "false") | |
: arg) | |
.ToArray(); | |
// create a new string based on the provided FormattableString | |
return FormattableStringFactory | |
.Create(str.Format, args) | |
.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment