Today, I just discovered the classroom. FormattableString Two years after it came out.
This class has been added with the functionality of string interpolation In C# 6.0.
String interpolation
String interpolation was a small revolution because it allowed us to make the code much clearer.
For example, to format a string I don't have to write:
string firstName = "jérémy";
var title = String.Format("{0} est heureux", firstName);
I can write more simply:
string firstName = "jérémy";
var title = $"{firstName} est heureux";
But what does this have to do with the FormattableString?
If you want to keep this string and the variables without calculating the string because you need to keep the two parts separate .NET provides the class FormattableString.
Its use is almost transparent:
string firstName = "jérémy";
FormattableString title = $"{firstName} est heureux";
By default any interpolated string can be used as a FormattableString without writing a single line of code.
Original illustration unavailable
Example of use
One of the interesting uses might be to want to transform a FormattableString In an encrypted URL string.
private string ToUrlFriendly(FormattableString formattableString)
{
var args = formattableString.GetArguments().Select(arg => WebUtility.UrlEncode(arg.ToString())).ToArray();
return string.Format(formattableString.Format, args);
}
L’use of the function is very simple:
string search = "jérémie est heureux youtube";
var url = ToUrlFriendly($"https://www.google.com/search?q={search}");
Generate:
https://www.google.com/search?q=j%C3%A9r%C3%A9mie+est+heureux+youtube
To go further:
Happy coding &##x1f642;
Thanks to Jeremy for reading it carefully.